1. 程式人生 > >Java跳過Https安全Get或Post訪問

Java跳過Https安全Get或Post訪問

為了方便以後使用,記錄一下。

一、證書信任管理器

/**
 * MyX509TrustManager.java   2013-11-29
 *
 * Copyright(c) 2000-2013 Rain, All Rights Reserved.
 */
package com.rain.weixin.util;

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.X509TrustManager;

/**
 * 證書信任管理器(用於https請求)
 * 
 * @author Rain
 * @date 2013-11-29
 * @version 1.0
 */
public class MyX509TrustManager implements X509TrustManager {

	@Override
	public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
		// TODO Auto-generated method stub
	}

	@Override
	public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
		// TODO Auto-generated method stub
	}

	@Override
	public X509Certificate[] getAcceptedIssuers() {
		// TODO Auto-generated method stub
		return null;
	}

}
二、Get或Post請求工具類

/**
 * WeixinUtil.java   2013-11-29
 *
 * Copyright(c) 2000-2013 Rain, All Rights Reserved.
 */
package com.rain.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 org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.rain.weixin.AccessToken;
import com.rain.weixin.Menu;

/**
 * 微信工具類
 * 
 * @author Rain
 * @date 2013-11-29
 * @version 1.0
 */
public class WeixinUtil {
	private static Logger LOG = LoggerFactory.getLogger(WeixinUtil.class);
	// 獲取access_token的介面地址(GET) 限200(次/天) 
	public final static String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
	// 選單建立(POST) 限100(次/天)
	public static String menu_create_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";

	/**
	 * 發起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 = new JSONObject(buffer.toString());
		} catch (ConnectException ce) {
			LOG.error("Weixin server connection timed out.");
		} catch (Exception e) {
			LOG.error("https request error:{}", e);
		}
		return jsonObject;
	}

	/**
	 * 獲取access_token
	 * 
	 * @param appid 憑證  
	 * @param appsecret 金鑰
	 * @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 (null != jsonObject) {
			try {
				accessToken = new AccessToken();
				accessToken.setToken(jsonObject.getString("access_token"));
				accessToken.setExpiresIn(jsonObject.getInt("expires_in"));
			} catch (JSONException e) {
				accessToken = null;// 獲取token失敗 
				LOG.error("獲取token失敗 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
			}
		}
		return accessToken;
	}

	/**
	 * 建立選單
	 * 
	 * @param menu 選單例項
	 * @param accessToken 有效的access_token
	 * @return 0表示成功,其他值表示失敗
	 */
	public static int createMenu(Menu menu, String accessToken) {
		int result = 0;
		// 拼裝建立選單的url
		String url = menu_create_url.replace("ACCESS_TOKEN", accessToken);
		// 將選單物件轉換成json字串
		String jsonMenu = JacksonXmlUtil.object2Json(menu);
		LOG.info("menu:" + jsonMenu);
		// 呼叫介面建立選單
		JSONObject jsonObject = httpRequest(url, "POST", jsonMenu);
		if (null != jsonObject) {
			if (0 != jsonObject.getInt("errcode")) {
				result = jsonObject.getInt("errcode");
				LOG.error("建立選單失敗 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
			}
		}

		return result;
	}
}