对HttpClient方法的封装

对HttpClient类使用的封装,方便使用,每个方法都写了注释,看着注释使用即可

封装的目的:包括访问页面或者支付支付、微信支付等api接口都是http/https请求,调用这些api的核心就是使用http/https请求,所有将这些请求封装方便使用

设置的参数可以针对各自的项目自行修改(直接用也可以,可以满足普通项目需求)

不对的地方请各位指正

简要说一下HttpClient使用的步骤(代码里也有注释),其实很简单:
创建Http请求实例 → 设置参数信息 → 执行请求并接收响应信息→ 处理响应信息 → 释放资源

package com.guxing.util;

import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.*;
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 java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 对http/https操作的封装,HttpClient的版本4.5.3
 * Created by qsh on 17/2/16.
 */
public class HttpClientUtil {

    private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

    private static CloseableHttpClient httpClient = null;
    public static final String CHARSET = "UTF-8";

    public static final String METHOD_GET = "GET";
    public static final String METHOD_POST = "POST";

    static {
        /**
         *  请求参数配置
         *  connectionRequestTimeout: 单位:毫秒
         *                          从连接池中获取连接的超时时间,超过该时间未拿到可用连接,
         *                          会抛出org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool
         *  connectTimeout: 单位:毫秒
         *                  连接上服务器(握手成功)的时间,超出该时间抛出connect timeout
         *  socketTimeout: 单位:毫秒
         *                  服务器返回数据(response)的时间,超过该时间抛出read timeout
         */
        httpClient = HttpClients.custom().setDefaultRequestConfig(RequestConfig.custom()
                .setConnectionRequestTimeout(2000).setConnectTimeout(2000).setSocketTimeout(2000).build()).build();
    }

    /**
     * 发送Http get请求
     * 如果url是拼接好参数的, 那么params设为null
     *
     * @param url 请求的url地址 ?之前的地址 eg:http://www.baidu.com
     * @param params 请求的参数
     * @return
     */
    public static final String doGet(String url, Map
    
    
     
      params) {
        return doGet(url, params, CHARSET);
    }

    /**
     * 发送Http post请求
     * @param url
     * @param params
     * @return
     */
    public static final String doPost(String url, Map
     
     
      
       params) {
        return doPost(url, params, CHARSET);
    }

    /**
     * 发送Http post请求
     * @param url
     * @param params JSON 或者 XML 字符串
     * @return
     */
    public static final String doPost(String url, String params) {
        return doPost(url, params, CHARSET);
    }


    public static final String doGet(String url, Map
      
      
       
        params, String charset) {

        if (StringUtils.isBlank(url)) {
            // url为空, 返回null
            return null;
        }
        try {
            /*
             * 参数处理 拼接参数到url
             */
            if (params != null && !params.isEmpty()) {
                List
       
       
        
         pairs = new ArrayList
        
        
          (params.size()); for (Map.Entry 
         
           entry : params.entrySet()) { String value = entry.getValue(); if (value != null) { pairs.add(new BasicNameValuePair(entry.getKey(), value)); } } url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset)); } HttpGet httpGet = new HttpGet(url); // 执行http get请求 CloseableHttpResponse response = httpClient.execute(httpGet); // 返回码校验 int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { httpGet.abort(); // logger.error("http请求".concat(url).concat("失败,error status code :").concat(String.valueOf(statusCode))); logger.error("http请求{}失败, error status code : {}", url, statusCode); } /* * 读取响应结果 */ HttpEntity entity = response.getEntity(); String result = null; if (entity != null) { result = EntityUtils.toString(entity, "utf-8"); } /* * 释放资源 */ EntityUtils.consume(entity); response.close(); return result; } catch (Exception e) { logger.error("url : {} http client request exception:{}", url, e); } return null; } public static final String doPost(String url, Map 
          
            params, String charset) { if (StringUtils.isBlank(url)) { return null; } try { List 
           
             pairs = null; if (params != null && !params.isEmpty()) { pairs = new ArrayList 
            
              (params.size()); for (Map.Entry 
             
               entry : params.entrySet()) { String value = entry.getValue(); if (value != null) { pairs.add(new BasicNameValuePair(entry.getKey(), value)); } } } HttpPost httpPost = new HttpPost(url); if (pairs != null && pairs.size() > 0) { httpPost.setEntity(new UrlEncodedFormEntity(pairs, charset)); } CloseableHttpResponse response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { httpPost.abort(); logger.error("http请求{}失败, error status code : {}", url, statusCode); } HttpEntity entity = response.getEntity(); String result = null; if (entity != null) { result = EntityUtils.toString(entity, "utf-8"); } EntityUtils.consume(entity); response.close(); return result; } catch (Exception e) { logger.error("url : {} http client request exception:{}", url, e); } return null; } public static final String doPost(String url, String params, String charset) { if (StringUtils.isBlank(url)) { return null; } try { HttpPost httpPost = new HttpPost(url); StringEntity reqEntity = new StringEntity(params, charset); httpPost.setEntity(reqEntity); CloseableHttpResponse response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { httpPost.abort(); logger.error("http请求{}失败, error status code : {}", url, statusCode); } HttpEntity entity = response.getEntity(); String result = null; if (entity != null) { result = EntityUtils.toString(entity, "utf-8"); } EntityUtils.consume(entity); response.close(); return result; } catch (Exception e) { logger.error("url : {} http client request exception:{}", url, e); } return null; } /** * 发送https请求 * 此处的返回值类型可以根据项目情况来定,也可以直接返回String类型 * @param requestUrl * 请求地址 * @param requestMethod * 请求方式(GET、POST)HttpClientUtil.METHOD_GET, HttpClientUtil.METHOD_POST * @param paramStr * 提交的数据: JsonStr或者XMLStr * @return JSONObject (通过JSONObject.get(key)的方式获取json对象的属性值) */ public static final JSONObject httpsRequest(String requestUrl, String requestMethod, String paramStr) { JSONObject jsonObject = null; 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 conn = (HttpsURLConnection) url.openConnection(); conn.setSSLSocketFactory(ssf); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); // 设置请求方式(GET/POST) conn.setRequestMethod(requestMethod); // 当outputStr不为null时向输出流写数据 if (null != paramStr) { OutputStream outputStream = conn.getOutputStream(); // 注意编码格式 outputStream.write(paramStr.getBytes("UTF-8")); outputStream.close(); } // 从输入流读取返回内容 InputStream inputStream = conn.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader( inputStream, "utf-8"); BufferedReader bufferedReader = new BufferedReader( inputStreamReader); String str = null; StringBuffer buffer = new StringBuffer(); while ((str = bufferedReader.readLine()) != null) { buffer.append(str); } // 释放资源 bufferedReader.close(); inputStreamReader.close(); inputStream.close(); inputStream = null; conn.disconnect(); jsonObject = JSONObject.fromObject(buffer.toString()); } catch (ConnectException ce) { logger.error("连接{}超时:{}", requestUrl, ce); } catch (Exception e) { logger.error("https请求{}异常:{}", requestUrl, e); } return jsonObject; } private static class MyX509TrustManager implements X509TrustManager { // 检查客户端证书 @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } // 检查服务器端证书 @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } // 返回受信任的X509证书数组 @Override public X509Certificate[] getAcceptedIssuers() { return null; } } } 
              
             
            
           
          
        
       
       
      
      
     
     
    
    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值