package org.nercita.weixin.util; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.X509TrustManager; /** * Certificate Trust Manager (for https requests) * The role of this certificate manager is to make it trust the certificate we specify. The following code means to trust all certificates, whether issued by an authority or not. * @author zhangwenchao * */ public class MyX509TrustManager implements X509TrustManager{ @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } }
package org.nercita.weixin.util; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.ConnectException; import java.net.URL; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import net.sf.json.JSONException; import net.sf.json.JSONObject; import org.nercita.weixin.domain.AccessToken; import org.nercita.weixin.domain.Menu; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Common interface tools for public platforms * User implements https request * @author zhangwenchao * */ public class HttpsRequestUtil { private static Logger logger = LoggerFactory.getLogger(HttpsRequestUtil.class); // Get the address of the access_token interface (GET), limited to 200 (times/day) public final static String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET"; // Menu creation (POST) limited to 100 (times/day) public static String menu_create_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN"; /** * Initiate an https request and get the result * * @param requestUrl request address * @param requestMethod request method (GET, POST) * @param outputStr Submitted data * @return JSONObject (get the attribute value of the json object by JSONObject.get(key)) */ public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) { JSONObject jsonObject = null; StringBuffer buffer = new StringBuffer(); try { // Create an SSLContext object and initialize it with our specified trust manager TrustManager[] tm = { new MyX509TrustManager() }; SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, tm, new java.security.SecureRandom()); // Get the SSLSocketFactory object from the above SSLContext object SSLSocketFactory ssf = sslContext.getSocketFactory(); //open connection URL url = new URL(requestUrl); HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection(); httpUrlConn.setSSLSocketFactory(ssf); httpUrlConn.setDoOutput(true); httpUrlConn.setDoInput(true); httpUrlConn.setUseCaches(false); // Set the request method (GET/POST) httpUrlConn.setRequestMethod(requestMethod); if ("GET".equalsIgnoreCase(requestMethod)){ httpUrlConn.connect(); } // when there is data to submit if (null != outputStr) { OutputStream outputStream = httpUrlConn.getOutputStream(); // Pay attention to the encoding format to prevent Chinese garbled characters outputStream.write(outputStr.getBytes("UTF-8")); outputStream.close(); } // Convert the returned input stream to a string 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(); // release resources 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; } /** * Get access_token * WeChat server will return data in json format: {"access_token":"ACCESS_TOKEN","expires_in":7200} * @param appid credentials * @param appsecret key * @return */ public static AccessToken getAccessToken(String appid, String appsecret) { AccessToken accessToken = null; String requestUrl = access_token_url.replace("APPID", appid).replace("APPSECRET", appsecret); JSONObject jsonObject = httpRequest(requestUrl, "GET", null); // if the request was successful if (null != jsonObject) { try { accessToken = new AccessToken(); accessToken.setAccessToken(jsonObject.getString("access_token")); accessToken.setExpiresIn(jsonObject.getInt("expires_in")); } catch (JSONException e) { accessToken = null; // Failed to get token logger.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg")); } } return accessToken; } /** * Create menu * * @param menu menu instance * @param accessToken valid access_token * @return 0 for success, other values for failure */ public static int createMenu(Menu menu, String accessToken) { int result = 0; // assemble the url to create the menu String url = menu_create_url.replace("ACCESS_TOKEN", accessToken); // Convert menu object to json string String jsonMenu = JSONObject.fromObject(menu).toString(); // Call the interface to create the menu JSONObject jsonObject = httpRequest(url, "POST", jsonMenu); if (null != jsonObject) { if (0 != jsonObject.getInt("errcode")) { result = jsonObject.getInt("errcode"); logger.error("Failed to create menu errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg")); } } return result; } }