简单封装下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

猜你喜欢

转载自blog.csdn.net/ardo_pass/article/details/54314658
今日推荐