引入依赖:
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
调用方法:
//注意引入包是否正确
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
public static String getToken(){
// 企业id
String corpid = "wx15687db123";
// 应用对应的secretID
String corpsecret = "31ux_biu6-456fgdf45578QHE-daZT32gzoI";
String access_token = "";
HttpClient client = new HttpClient();
String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpid + "&corpsecret=" + corpsecret + "";
GetMethod get = new GetMethod(url);
try {
int executeMethod = client.executeMethod(get);
System.out.println(executeMethod);
access_token = get.getResponseBodyAsString();
System.out.println(access_token);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return access_token;
}
当然不能频繁调用gettoken接口,否则会受到频率拦截,access_token的有效期正常情况下为7200秒(2小时),因此我们需要将token保存在缓存中,两小时之内从缓存中获取,超过两小时再重新调接口获取token,可以通过redis等缓存技术实现,如果单单只是简单测试可以引用hutool实现,见下篇Spring Boot引入hutool实现简单缓存技术_心寒丶的博客-CSDN博客

该博客介绍了如何在Java中通过Apache HttpClient库来获取微信企业号的access_token。首先,需要在项目中引入commons-httpclient依赖,然后设置企业id和secretID,构造HTTP GET请求并执行。成功获取到access_token后,建议将其保存在缓存中,如Redis,以避免频繁调用接口导致的限制。对于简单的测试,可以使用Hutool实现简单的缓存管理。
6688





