首先准备好常量类,当然也可以写到配置文件里
/**
*
* 功能描述: 公用封装方法 <br/>
* date: 2017-7-24 下午5:18:58 <br/>
* lk
*/
public interface Constant {
// 凭证获取(GET)
public final static String TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
// 用户同意授权,获取code
public final static String WX_OAUTH_URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";
// 用户同意授权,回调url
public final static String WX_REDIRECT_URL = "回调url";
// 拉去用户信息url
public final static String WX_SNSAPI_URL = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
//微信openId
public final static String WX_OPEN_ID = "公众好id";
//微信appSecret
public final static String WX_APP_SECRET = "appSecret";
}
然后需要几个工具类
/**
*
* 功能描述: 公用封装方法 <br/>
* date: 2017-7-24 下午5:18:58 <br/>
* lk
*/
public class CommonMethod {
/**
* 获取接口访问凭证
*
* @param appid 凭证
* @param appsecret 密钥
* @return
*/
public static Token getToken(String appid, String appsecret, String code) {
Token token = null;
String requestUrl = Constant.TOKEN_URL.replace("APPID", appid).replace("SECRET", appsecret).replace("CODE", code);
// 发起GET请求获取凭证
net.sf.json.JSONObject jsonObject = httpsRequest(requestUrl, "GET", null);
if (null != jsonObject) {
try {
token = new Token();
token.setAccessToken(jsonObject.getString("access_token"));
token.setExpiresIn(jsonObject.getInt("expires_in"));
token.setOpenId(jsonObject.getString("openid"));
} catch (JSONException e) {
token = null;
// 获取token失败
System.out.println("获取token失败");
e.printStackTrace();