1. 程式人生 > >簡單封裝下rest api,支援http,https及代理模式

簡單封裝下rest api,支援http,https及代理模式

現在很多主流平臺採用rest方式的OpenAPI,例如小程式、聚合介面、公司內部介面、對外介面、微信介面等,很多采用rest輕量級資料傳輸的方式。

於是乎簡單封裝下rest請求api(其實就是幾個簡單java類,呵呵),可以實現http及https模式的請求,也支援JsessionId和代理模式,甚至系統自動傳送郵件的功能也是用此工具類實現的。


步入正題...

RestUtil api


RestParam api


程式碼

RestUtil.java

/**
 * rest請求通用介面工具類
 * 
 * @author ardo
 */
public class RestUtil {
	
    private static Logger log = LoggerFactory.getLogger(RestUtil.class);
	
	/**
	 * 發起http/https請求並獲取結果
	 */
    public static JSONObject httpRequest(RestParam restParam) {
        JSONObject jsonObject = null;
        // 建立代理伺服器
        InetSocketAddress addr = null;
        Proxy proxy = null;
        boolean ifProxyModel = restParam.getIfProxy()!=null && restParam.getIfProxy()!="" && "TRUE".equals(restParam.getIfProxy());
        
        if(ifProxyModel){
        	addr = new InetSocketAddress(restParam.getProxyAddress(), Integer.parseInt(restParam.getProxyPort()));
        	proxy = new Proxy(Proxy.Type.HTTP, addr); // http 代理
        	Authenticator.setDefault(new MyAuthenticator(restParam.getProxyUser(), restParam.getProxyPassWord()));// 設定代理的使用者和密碼
        }
        
        try {
            
            URL url = new URL(restParam.getReqUrl());
            if("https".equals(restParam.getReqHttpsModel())){
            	TrustManager[] tmCerts = new javax.net.ssl.TrustManager[1];
                tmCerts[0] = new SimpleTrustManager();
                try {
                    SSLContext sslContext = SSLContext.getInstance("SSL");
                    sslContext.init(null, tmCerts, null);
                    HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());

                    HostnameVerifier hostnameVerifier = new SimpleHostnameVerifier();
                    HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                HttpsURLConnection httpUrlConn = null;
                if(ifProxyModel){
                	httpUrlConn = (HttpsURLConnection) url.openConnection(proxy);
                }else{
                	httpUrlConn = (HttpsURLConnection) url.openConnection();
                }
            	
            	//httpUrlConn.setSSLSocketFactory(ssf);
            	jsonObject = ardoHttpsURLConnection(httpUrlConn, restParam.getReqMethod(), 
            		restParam.getReqContent(), restParam.getSessionId());
            }else{
            	HttpURLConnection httpUrlConn = null;
            	if(ifProxyModel){
            		httpUrlConn = (HttpURLConnection) url.openConnection(proxy);
            	}else{
            		httpUrlConn = (HttpURLConnection) url.openConnection();
            	}
            	jsonObject = ardoHttpURLConnection(httpUrlConn, restParam.getReqMethod(), 
            		restParam.getReqContent(), restParam.getSessionId());
            	
            }
            
        } catch (ConnectException ce) {
            log.error("API server connection timed out.");
            log.error("【rest連線異常資訊】"+ce.getMessage());
        } catch (Exception e) {
            log.error("API https or http request error:{}", e);
            log.error("【rest異常資訊】"+e.getMessage());
        }
        return jsonObject;
    }
    
    /**
     * http請求方法
     * @param httpUrlConn 請求路徑
     * @param requestMethod 請求型別POST|GET
     * @param outputStr 請求內容
     * @param sessionId sessionId(非必填)
     * @return JSONObject型別資料
     */
    public static JSONObject ardoHttpURLConnection(HttpURLConnection httpUrlConn, 
    		String requestMethod, String outputStr, String sessionId){
    	JSONObject jsonObject = null;
		StringBuffer buffer = new StringBuffer();
    	try {
    		
            //httpUrlConn = (HttpURLConnection) url.openConnection();

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            
            if(sessionId!=null && sessionId!=""){
                httpUrlConn.setRequestProperty("Cookie", "JSESSIONID="+sessionId);
            }
            
            // 設定請求方式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) {
            log.error("API server connection timed out.");
            log.error("【rest http連線異常資訊】"+ce.getMessage());
        } catch (Exception e) {
            log.error("API http request error:{}", e);
            log.error("【rest http異常資訊】"+e.getMessage());
        }
        return jsonObject;
    }
    
    /**
     * https請求方法
     * @param httpUrlConn 請求路徑
     * @param requestMethod 請求型別POST|GET
     * @param outputStr 請求內容
     * @param sessionId sessionId(非必填)
     * @return JSONObject型別資料
     */
    public static JSONObject ardoHttpsURLConnection(HttpsURLConnection httpUrlConn, 
    		String requestMethod, String outputStr, String sessionId){
    	JSONObject jsonObject = null;
		StringBuffer buffer = new StringBuffer();
    	try {
    		
            //httpUrlConn = (HttpsURLConnection) url.openConnection();
    		httpUrlConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            
            if(sessionId!=null && sessionId!=""){
                httpUrlConn.setRequestProperty("Cookie", "JSESSIONID="+sessionId);
            }
            
            //設定請求方式GET/POST
            httpUrlConn.setRequestMethod(requestMethod);
            httpUrlConn.setRequestProperty("Content-Type", "application/json");
            
            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) {
            log.error("API server connection timed out.");
            log.error("【rest https連線異常資訊】"+ce.getMessage());
        } catch (Exception e) {
            log.error("API https request error:{}", e);
            log.error("【rest https異常資訊】"+e.getMessage());
        }
        return jsonObject;
    }
    
    /**
     * 代理模式所需的認證
     * @author ardo
     *
     */
    static class MyAuthenticator extends Authenticator {
        private String user = "";
        private String password = "";
  
        public MyAuthenticator(String user, String password) {
            this.user = user;
            this.password = password;
        }
  
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(user, password.toCharArray());
        }
    }
    

    // test url
    //public static String menu_create_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
    
    
    private static class SimpleTrustManager implements TrustManager, X509TrustManager {

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

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

        
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    }
    
    private static class SimpleHostnameVerifier implements HostnameVerifier {

        
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }

    }
    
    public static void main(String[] args) {
    	//Test for rest
    	RestUtil.httpRequest(new RestParam("http://120.76.130.68/ardosms/v2email", "POST", "傳送內容,可以是html文字", 
    			"http", "", "TRUE", "proxy.xxx", "8080", "du...", "1zc3..."));
	}
}

RestParam.java
package com.ardo.api.rest;
/**
 * rest bean
 * 
 * 該bean作為RestUtil類方法引數
 * @author ardo
 * 
 */
public class RestParam {
	/**
	 * 請求url路徑
	 */
	private String reqUrl;
	/**
	 * 請求型別"POST"或"GET"
	 */
	private String reqMethod;
	/**
	 * 請求內容
	 */
	private String reqContent;
	/**
	 * 請求模式"https"或"http"(預設http)
	 */
	private String reqHttpsModel;
	/**
	 * 該值為空時不設定,不為空時設定
	 */
	private String sessionId;
	/**
	 * 是否開啟代理模式(預設FALSE)"TRUE":開啟;"FALSE":不開啟;設為TRUE時需要配置以下幾項引數
	 */
	private String ifProxy;
	/**
	 * 代理地址
	 */
	private String proxyAddress;
	/**
	 * 代理埠
	 */
	private String proxyPort;
	/**
	 * 代理賬號
	 */
	private String proxyUser;
	/**
	 * 代理密碼
	 */
	private String proxyPassWord;
	
	
	public RestParam() {
		super();
	}
	
	...省略
	
	
}

程式碼下載地址:http://download.csdn.net/download/ardo_pass/9733899