String code = get("code");
//创建httpClient请求
CloseableHttpClient httpClient = HttpClients.createDefault();
//请求地址
String url = "https://api.weixin.qq.com/sns/oauth2/access_token";
//创建httpPost
HttpPost httpPost = new HttpPost(url);
//创建 参数集合
List<NameValuePair> params = new ArrayList<NameValuePair>();
//添加参数
params.add(new BasicNameValuePair("appid" , Tools.appId));
params.add(new BasicNameValuePair("secret" , Tools.appSecret));
params.add(new BasicNameValuePair("code" , code));
params.add(new BasicNameValuePair("grant_type" , "authorization_code"));
//将参数集合添加到httpPost
try {
httpPost.setEntity(new UrlEncodedFormEntity(params));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
// 响应
CloseableHttpResponse resp = null;
try {
// 由客户端执行(发送)Post请求
resp = httpClient.execute(httpPost);
// 从响应模型中获取响应实体
HttpEntity responseEntity = resp.getEntity();
//System.out.println("响应状态为:" + resp.getStatusLine());
if (responseEntity != null) {
//System.out.println("响应内容长度为:" + responseEntity.getContentLength());
String content = EntityUtils.toString(responseEntity);
JSONObject obj = JSON.parseObject(content);
System.out.println("open_id=" + obj.get("openid"));
// System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 释放资源
if (httpClient != null) {
httpClient.close();
}
if (resp != null) {
resp.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
微信公众平台网页授权获取openid代码
最新推荐文章于 2024-06-23 23:51:42 发布