前面准备部分大体和这篇文章一致 https://developers.weixin.qq.com/community/develop/article/doc/000e4c0c26c720fc77f8973d451413
public static String getOpenid(String code) { String openid = null; Map<String, Object> rtnMap = new HashMap<String, Object>(); String url = "https://api.weixin.qq.com/sns/jscode2session"; url += "?appid=" + APPID;//自己的appid url += "&secret=" + AppSecret;//密匙 url += "&js_code=" + code; //你传入的code url += "&grant_type=authorization_code"; byte[] res = null; org.apache.http.client.HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url); HttpResponse response = null; try { response = httpclient.execute(httpget); res = IOUtils.toByteArray(response.getEntity().getContent()); } catch (Exception e) { } finally { if (httpget != null) { httpget.abort(); } httpclient.getConnectionManager().shutdown(); } com.alibaba.fastjson.JSONObject jo; try { jo = JSON.parseObject(new String(res, "utf-8")); openid = jo.getString("openid"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return openid;} |
这个代码基本功能可以实现。静态修饰是我为了偷懒而加上的。
