1.起因
因为项目要求需要在微信公众号上链接网站,所以需要用到,第一次弄,参考了许多大佬的文章。
2.参考文档
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115
3.相关代码
WeiXinUtil类
// 第一步:获得access_token代码
Map<String,String> map = new HashMap<String,String>();
map.put("grant_type",Constants.GRANT_TYPE); //填写自己的grant_type
map.put("appid",Constants.APPID); //填写自己的appid
map.put("secret",Constants.SECRET); //填写自己的secret
String returnStr = HttpUtil.doGet("https://api.weixin.qq.com/cgi-bin/token",map);
String url = "https://api.weixin.qq.com/cgi-bin/token";
String replace = returnStr.replace(url, ""); //通过appid和secret获得的请求结果
JSONObject json = null;
try {
json = JSONObject.fromObject(replace);
} catch (JSONException | IllegalArgumentException e1) {
e1.printStackTrace();
}
//获取请求结果中access_token的参数值
String accessToken = json.getString("access_token");
// 第二步:根据token获得js临时票据(有效时间7200秒,可以放到memcache)
Map<String,String> map2 = new HashMap<String,String>();
map2.put("access_token",accessToken);
map2.put("type","jsapi");
String returnStr2 = HttpUtil.doGet("https://api.weixin.qq.com/cgi- bin/ticket/getticket",map2);
// JSONObject json = JSONObject.fromObject(returnStr);
JSONObject formJson = null;
try {
String url2 = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
String replace2 = returnStr2.replace(url2, "");
formJson = JSONObject.fromObject(replace2);
} catch (JSONException | IllegalArgumentException e) {
e.printStackTrace();
}
//获取请求结果中ticket参数值
String ticket= formJson.getString("ticket");
// 第三步:对密钥进行sha1加密
long time = System.currentTimeMillis()/1000;
String randomStr = StringUtils.right(String.valueOf(System.currentTimeMillis()), 10);
//特别注意的是调用微信js,url必须是当前页面(转发的不行)
String url3 = Constants.URL;
String str = "jsapi_ticket=" + ticket + "&noncestr=" + randomStr+ "×tamp=" + time + "&url="+url3;
String signature = "";
try
{
MessageDigest crypt = MessageDigest.getInstance("SHA-1");
crypt.reset();
crypt.update(str.getBytes("UTF-8")); //对string1 字符串进行SHA-1加密处理
signature = EncryptUtil.byteToHex(crypt.digest()); //对加密后字符串转成16进制
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
throw new Exception("signature生成失败!");
}
org.json.JSONObject jsonObj = new org.json.JSONObject();
// jsonObj.put("accessToken", accessToken);
jsonObj.put("url", url3);
jsonObj.put("jsapi_ticket", ticket);
jsonObj.put("timestamp", time);
jsonObj.put("nonceStr",randomStr);
jsonObj.put("signature",signature);
HttpUtil类,doGet方法
/**
*
* @param url
* @param params
* @return String
* @throws HttpException
*
* 通过get方式请求指定url,通过map方式传入参数
*/
public static String doGet(String url,Map<String,String> params) throws HttpException{
HttpClient client = new HttpClient();
StringBuilder sb = new StringBuilder(url);
StringBuilder responseBody = new StringBuilder(url);
InputStream ins = null;
if(params.size() > 0)
sb.append("?");
for (Entry<String, String> map: params.entrySet()) {
String pramName = map.getKey();
String values = map.getValue();
sb.append(pramName+"="+values);
sb.append("&");
}
try {
GetMethod method = new GetMethod(sb.toString().substring(0, sb.length()));
int statusCode = client.executeMethod(method);
if (statusCode == HttpStatus.SC_OK) {
ins = method.getResponseBodyAsStream();
byte[] b = new byte[1024];
int r_len = 0;
while ((r_len = ins.read(b)) > 0) {
responseBody.append(new String(b, 0, r_len, method . getResponseCharSet()));
}
}
} catch (IOException e) {
logger.error(e.toString());
}
return responseBody.toString();
}
HttpUtil类,httpRequest方法
/**
* 描述: 发起https请求并获取结果
* @param requestUrl 请求地址
* @param requestMethod 请求方式(GET、POST)
* @param outputStr 提交的数据
* @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
*/
public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
try {
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 设置请求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);
if ("GET".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();
// 当有数据需要提交时
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
// 注意编码格式,防止中文乱码
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 将返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
jsonObject = JSONObject.fromObject(buffer.toString());
} catch (ConnectException ce) {
logger.error("Weixin server connection timed out.");
} catch (Exception e) {
logger.error("https request error:{}", e);
}
return jsonObject;
}
可通过以上两个方法请求相应url来获取请求结果,这里主要用到doGet方法。。建议使用httpRequest方法,因为后面处理access_token的缓存用到,toGet只能用于get方式请求,httpRequest可以用于get或者post方式使用更方便。