1. 程式人生 > >微信開發的Http或Https常用工具類

微信開發的Http或Https常用工具類

前不久寫了幾篇有關微信定製開發的文章並整理成了專題,裡面所有的文件都提到了CommonUtil這個工具類,關於這個工具類原本有寫但是不是每篇部落格都有,所以就有人找我要這個工具類,評論裡也有好多人說不知道這個工具類怎麼寫,因此針對這些疑問就特意給大家貼一下程式碼

1  由於https使用還是比較多,因此要寫一個請求時需要用到的認證程式碼,因java就自帶,只需實現X509TrustManager即可

package com.debug.weixin.util;

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

import javax.net.ssl.X509TrustManager;

public class MyX509TrustManager implements X509TrustManager {

	public void checkClientTrusted(X509Certificate[] chain, String authType)
			throws CertificateException {
	}

	public void checkServerTrusted(X509Certificate[] chain, String authType)
			throws CertificateException {
	}

	public X509Certificate[] getAcceptedIssuers() {
		return null;
	}
}



方法體不用寫任何程式碼,後面的工具類就會使用到我們寫的這個方法了

2  編寫CommonUtil

package com.debug.weixin.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.HttpURLConnection;
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.JSONObject;

public class CommonUtil {
	
	public static JSONObject httpsRequest(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) {  
            ce.printStackTrace();
        } catch (Exception e) {  
            e.printStackTrace();
        }  
        return jsonObject;  
    }
	
    public static String httpRequest(String requestUrl, String requestMethod, String outputStr) { 
		
        
        StringBuffer buffer = new StringBuffer();  
        try {  
          
  
            URL url = new URL(requestUrl);  
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();  
           
  
            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) {  
            ce.printStackTrace();
        } catch (Exception e) {  
            e.printStackTrace();
        }  
        return buffer.toString();  
    }
	public static String urlEncodeUTF8(String source){
		String result = source;
		try {
			result = java.net.URLEncoder.encode(source,"utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return result;
	}
	
    public static String httpsRequestForStr(String requestUrl, String requestMethod, String outputStr) { 
		
        String result="";
        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();  
            result=buffer.toString();  
        } catch (ConnectException ce) {  
            ce.printStackTrace();
        } catch (Exception e) {  
            e.printStackTrace();
        }  
        return result;  
    }
}


工具類封裝了各類請求以及不同返回值的方法,要注意加入json的開發jar包,否則會報錯;關於上面的程式碼也有替代的方法,那就是使用HttpClient,使用哪一種可根據自己或公司的實際情況選擇