坚持把遇到的问题整理出来,供大家参考(企鹅群:263130304),转载注明出处(方便大家找我要源码),对你有帮助请点个赞,如果存在不足之处请留意,不喜勿喷,欢迎大家相互交流学习。——沙果
一、获取code:
1、这里可以直接写在js里
location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=替换APPID&redirect_uri=替换回调地址&response_type=code&scope=snsapi_base&state=STATE%23wechat_redirect&connect_redirect=1#wechat_redirect';
2、在回调地址中获取code
var code = $.getUrlParam("code");
二、获取openid:
// 创建HttpClientBuilder
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
// HttpClient
CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
HttpGet httpGet = new HttpGet(urlOpenid + "?appid=替换APPID&secret=替换secret&code=替换code&grant_type=authorization_code");
try {
HttpResponse httpResponse = closeableHttpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
String result = EntityUtils.toString(httpEntity, "UTF-8");
// 过滤
result = result.replaceAll("", "");
String sTotalString = result;
// 把字符串转换为JSONArray对象
JSONObject jsonObject = JSONObject.fromObject(sTotalString);
if (jsonObject.get("openid") != null) {
return jsonObject.get("openid").toString();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 释放资源
try {
closeableHttpClient.close();
} catch (IOException e) {
}
}
说明:
1、getUrlParam自定义获取参数方法
2、将文中“替换”部分修改以外,其他部分可以不用修改