备注:测试基于微信公众平台测试号编写,真实开发环境基本适用
access_token的介绍可以参考微型开放平台的官方文档:https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html
下面是java的具体实现方法:
首先要先引入pom依赖:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
然后是具体实现的代码:
/**
* 获取acces
*/
@RequestMapping("/getaccess")
@ResponseBody
public static String getaccess() {
HttpClient httpClient = HttpClientBuilder.create().build();
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+appsecret;
HttpGet request = new HttpGet(url);
try {
HttpResponse response = httpClient.execute(request);
InputStreamReader inputStreamReader = new InputStreamReader(response.getEntity().getContent());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
String str = sb.toString();
Map maps = (Map)JSON.parse(str);
String string = maps.get("access_token").toString();
return string;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
这样就可以获取到access_token的值了,这里只是简单的获取,并不涉及到保存。如果没有获取到要根据错误代码来检查哪里出了问题。
参考链接:https://blog.csdn.net/xiaoyao2246/article/details/86623217