闲暇时间写了个简单的获取微信公众号的access_token,当然只是简单的获取,而且有效期是两小时,之后可以考虑使用定时任务定时获取access_token,废话不多说了,贴上代码咯
import java.io.IOException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;
import com.loup.api.message.GetAccessTokenRsp;
/**
* 获取微信access_token工具类
* <一句话功能简述>
*
* @author xlp
* @version [V1.00, 2016年10月22日]
* @see [相关类/方法]
* @since V1.00
*/
public class WeiXinAccessTokenUtil
{
private static final Logger DEBUG_LOGGER = Logger.getLogger(WeiXinAccessTokenUtil.class);
/**
*
* 获取微信access_token
* <功能详细描述>
* @param appid
* @param secret
* @return
* @see [类、类#方法、类#成员]
*/
public static GetAccessTokenRsp getWeiXinAccessToken(String appid,String secret)
{
if(StringUtils.isEmpty(appid)|| StringUtils.isEmpty(secret))
{
DEBUG_LOGGER.error("appid or secret is null");
return null;
}
GetAccessTokenRsp getAccessTokenRsp = new GetAccessTokenRsp();
try
{
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret;
HttpClient httpClient = new HttpClient();
GetMethod getMethod = new GetMethod(url);
int execute = httpClient.executeMethod(getMethod);
System.out.println("execute:"+execute);
String getResponse = getMethod.getResponseBodyAsString();
getAccessTokenRsp.setAccessToken(getResponse);
}
catch (IOException e)
{
DEBUG_LOGGER.error("getAccessToken failed,desc:::"+e);
e.printStackTrace();
}
System.out.println(getAccessTokenRsp);
return getAccessTokenRsp;
}
}
package com.loup.api.message;
import java.io.Serializable;
public class GetAccessTokenRsp implements Serializable
{
/**
* serialVersionUID
*/
private static final long serialVersionUID = -7021131613095678023L;
private String accessToken;
public String getAccessToken()
{
return accessToken;
}
public void setAccessToken(String accessToken)
{
this.accessToken = accessToken;
}
@Override
public String toString()
{
return "GetAccessTokenRsp [accessToken=" + accessToken + "]";
}
}