1.定义常量实体类
//class WechatConfig
/**
* 微信配置类一
*/
public class WechatConfig {
public static final String appID = "xxxxxxxxx";
public static final String appsecret = "xxxxxxx";
}
2定义响应/参数实体类
//此处使用了lombok 驱动包,用来省写set和get
@Data
public class AccessTokenEntity {
private String accessToken;
private int expiresIn;
}
3.封装接口
public static AccessTokenEntity getAccessTokenAndTime() throws IOException {
//使用默认配置创建httpclient实例
CloseableHttpClient httpClient = HttpClients.createDefault();
//配置超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000).setConnectionRequestTimeout(5000)
.setSocketTimeout(5000).setRedirectsEnabled(true)
.build();
//声明url字符串变量,并复制
String oldurl ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
//替换字符串的两个值
String newurl = oldurl.replace("APPID", WechatConfig.appID).replace("APPSECRET",WechatConfig.appsecret).trim();
//http请求,并装配url地址
HttpGet httpGet = new HttpGet(newurl);
//http请求,装配配置超时时间
httpGet.setConfig(requestConfig);
try {
//httpclient执行请求,返回响应
HttpResponse response = httpClient.execute(httpGet);
//声明响应变量字符串
String result = "";
//用string接受响应实体内容
result = EntityUtils.toString(response.getEntity(),"utf-8");
//内容里带有下划线的变量全部替换成小驼峰命名
String newResult = result.replace("access_token","accessToken").replace("expires_in","expiresIn");
//string 转jsonObject
JSONObject jsonObject = JSONObject.fromObject(newResult);
//jsonObject 转 javaBean
AccessTokenEntity accessTokenEntity = (AccessTokenEntity) JSONObject.toBean(jsonObject ,AccessTokenEntity.class);
return accessTokenEntity;
} catch (IOException e) {
e.printStackTrace();
}finally {
httpClient.close();
}
return null;
}
只要正确配置密钥,最后测试,,即可看到效果。
需要用到的maven驱动包
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sf.json-lib/json-lib -->
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>