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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: C封装好的支持HTTP/HTTPS类是指在C语言中封装好的、用于支持HTTPHTTPS协议的类或库。 HTTP(超文本传输协议)是一种用于客户端和服务器之间进行通信的协议,它通过请求-响应的方式在Web上传输超文本。HTTPS是在HTTP基础上加入了安全层的协议,通过使用SSL/TLS加密来保护数据传输的安全性。 C语言作为一种较底层的编程语言,能够在嵌入式系统和一些对性能要求较高的场景中发挥重要作用。在网络通信方面,C语言也有一些库或类可以支持HTTP/HTTPS协议。这些库或类通常会提供一些函数或方法,用于执行HTTP/HTTPS请求,包括发送请求、获取响应、解析响应等。 在C语言中,可以使用一些成熟的开源库来完成这些功能,比如cURL(libcurl)、libhttps等。cURL是一种功能丰富、可靠性较高的开源网络传输工具,它可以支持多种网络协议,包括HTTPHTTPS。cURL提供了一套简单易用的API,可以在C语言中直接调用,实现HTTP/HTTPS请求和响应的处理。 使用cURL库,开发人员可以通过简单的代码实现HTTP/HTTPS请求,并对响应进行处理。开发人员可以设置请求的URL、请求方法(GET、POST)、请求头、请求体等信息,并可以获取到服务器返回的响应数据。同时,cURL也支持HTTPS请求的加密功能,确保数据传输的安全性。 总之,C封装好的支持HTTP/HTTPS类通常是指在C语言中使用HTTP/HTTPS通信的库或类,比较常用的有cURL库等。这些库提供了实现HTTP/HTTPS请求和响应处理的功能,可以方便地在C语言项目中使用。 ### 回答2: C 封装好的支持 HTTP/HTTPS 类是指在编程语言中提供的一个已经封装好的类库或模块,用于简化开发者在创建和处理 HTTP/HTTPS 请求与响应的过程。这样的类通常提供了一系列的方法和属性,可以实现与 HTTP/HTTPS 协议相关的功能。 该类通常具有以下特点: 1. 支持HTTP/HTTPS:该封装类旨在支持 HTTPHTTPS 协议,因此可以在开发的应用程序中使用这些协议来进行网络通信。 2. 简化请求:该类提供了一套简单易用的方法,使开发者能够轻松地创建和发送 HTTP/HTTPS 请求,并设置请求的头部、正文和参数等。 3. 处理响应:该类还具备处理 HTTP/HTTPS 响应的能力,包括解析服务器返回的响应头部和提取响应正文等。 4. 支持安全性:由于支持 HTTPS,该类可提供安全的通信方式,使用 SSL/TLS 协议进行加密和验证,确保数据在网络传输过程中的安全性。 5. 具备错误处理:该类还具备处理异常和错误的机制,可以通过捕获异常或错误来进行错误处理,提高代码的健壮性和可靠性。 6. 高性能:该类在设计上追求高性能和高效率,可以处理大量并发请求,并通过使用连接池和多线程等技术来提升网络请求的效率。 使用该封装好的支持 HTTP/HTTPS 类可以大大简化开发者的工作,减少开发时间和代码复杂度,同时提供了一种可靠和安全的方式来进行 HTTP/HTTPS 协议的通信。开发者只需使用该类提供的方法和属性,即可实现与服务器的交互,发送请求并获取响应。 ### 回答3: C封装好的支持HTTP/HTTPS类是指一种已经封装完成的能够支持HTTPHTTPS协议的类。在计算机编程中,HTTPHTTPS协议被广泛用于在互联网上进行数据传输和通信。这种封装好的类可以在程序中直接调用,无需再自己实现HTTP/HTTPS相关的功能。 这样的类通常提供了一系列的方法和属性,用于发送HTTP/HTTPS请求和接收响应。可以通过这个类来进行GET请求,POST请求,以及其他常用的HTTP方法。该类还可以处理请求的返回结果,解析服务器返回的数据,并且提供了错误处理机制,用于处理请求过程中的错误。 封装好的类还可能提供了一些额外的功能,如支持HTTP代理,设置请求头,设置请求超时时间等等。这些功能可以根据具体的业务需求来选择使用。 使用C封装好的支持HTTP/HTTPS类,可以极大地简化开发过程,提高开发效率。开发者无需再关注底层的HTTP/HTTPS实现细节,而是直接使用封装好的类来完成所需的HTTP/HTTPS操作。 总的来说,C封装好的支持HTTP/HTTPS类是一个已经封装好的用于实现HTTP/HTTPS协议通信的类,通过使用这个类,开发者可以更加方便地进行HTTP/HTTPS请求和接收响应。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值