java获取微信accessToken的方法
本文实例为大家分享了java如何获取微信accessToken,供大家参考,具体内容如下
packagecom.fengdi.lianmeng.task;
importcom.fengdi.lianmeng.common.CacheHelper;
importcom.fengdi.lianmeng.util.http.HttpRequest;
importcom.fengdi.lianmeng.util.tencent.CloudSignHelper;
importcom.fengdi.lianmeng.util.tencent.Interface;
importnet.sf.json.JSONObject;
importorg.quartz.JobExecutionContext;
importorg.slf4j.Logger;
importorg.slf4j.LoggerFactory;
/**
*定时获取微信accessToken
*/
publicclassGetWeiXinAccessTokenTask{
privatestaticLoggerlogger=LoggerFactory.getLogger(GetWeiXinAccessTokenTask.class);
/**
*每90分钟,获取一次微信accessToken
*/
publicvoidgetWeiXinAccessToken(JobExecutionContextcontext){
try{
logger.info("获取微信定时AccessToken任务启动了");
//封装请求数据
Stringparams="grant_type=client_credential"+
"&secret="+CloudSignHelper.wxspSecret+//小程序的app_secret(在微信小程序管理后台获取)
"&appid="+CloudSignHelper.appid;//小程序唯一标识appid(在微信小程序管理后台获取)
//发送GET请求
Stringresult=HttpRequest.sendGet("https://api.weixin.qq.com/cgi-bin/token",params);
//解析相应内容(转换成json对象)
JSONObjectjsonObject=JSONObject.fromObject(result);
StringaccessToken=(String)jsonObject.get("access_token");
CacheHelper.put("wxAccessToken",accessToken);//将accessToken放入缓存,用的时候取就行
logger.info("获取微信定时AccessToken任务结束了");
}catch(Exceptionex){
logger.error("获取微信定时AccessToken任务失败.",ex);
}
}
}
GET请求
publicstaticStringsendGet(Stringurl,Stringparam){
Stringresult="";
BufferedReaderin=null;
try{
StringurlNameString=url+"?"+param;
URLrealUrl=newURL(urlNameString);
//打开和URL之间的连接
URLConnectionconnection=realUrl.openConnection();
//设置通用的请求属性
connection.setRequestProperty("accept","*/*");
connection.setRequestProperty("connection","Keep-Alive");
connection.setRequestProperty("user-agent","Mozilla/4.0(compatible;MSIE6.0;WindowsNT5.1;SV1)");
//建立实际的连接
connection.connect();
//获取所有响应头字段
Map>map=connection.getHeaderFields();
//遍历所有的响应头字段
for(Stringkey:map.keySet()){
System.out.println(key+"--->"+map.get(key));
}
//定义BufferedReader输入流来读取URL的响应
in=newBufferedReader(newInputStreamReader(connection.getInputStream()));
Stringline;
while((line=in.readLine())!=null){
result+=line;
}
}catch(Exceptione){
System.out.println("发送GET请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输入流
finally{
try{
if(in!=null){
in.close();
}
}catch(Exceptione2){
e2.printStackTrace();
}
}
returnresult;
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。