HttpClientUtils封装(详细版本)

参考链接:https://www.cnblogs.com/codingmode/p/10881876.html

1、关键 JAR

 org.apache.httpcomponents

  httpclient

  4.5.2

  commons-io

  commons-io

  2.4

2、封装工具类(HttpClientUtils)

//

// Source code recreated from a .class file by IntelliJ IDEA

// (powered by Fernflower decompiler)

//

package com.tree.ztree_demo.httpclient;

import java.io.IOException;

import java.io.InputStream;

import java.net.URI;

import java.net.URISyntaxException;

import java.nio.charset.Charset;

import java.security.GeneralSecurityException;

import java.security.KeyStore;

import java.security.cert.CertificateException;

import java.security.cert.X509Certificate;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.Iterator;

import java.util.List;

import java.util.Map;

import java.util.Map.Entry;

import javax.net.ssl.SSLContext;

import javax.net.ssl.SSLException;

import javax.net.ssl.SSLSession;

import javax.net.ssl.SSLSocket;

import org.apache.commons.io.IOUtils;

import org.apache.http.HttpEntity;

import org.apache.http.NameValuePair;

import org.apache.http.client.config.RequestConfig;

import org.apache.http.client.config.RequestConfig.Builder;

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.client.utils.URIBuilder;

import org.apache.http.conn.ssl.SSLConnectionSocketFactory;

import org.apache.http.conn.ssl.SSLContextBuilder;

import org.apache.http.conn.ssl.TrustStrategy;

import org.apache.http.conn.ssl.X509HostnameVerifier;

import org.apache.http.entity.StringEntity;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClients;

import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

import org.apache.http.message.BasicNameValuePair;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.util.StringUtils;

public class HttpClientUtils {

  private static Logger LOG = LoggerFactory.getLogger(HttpClientUtils.class);

  private static PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager();

  private static RequestConfig requestConfig;

  private static final int MAX_TOTAL = 100;

  private static final int MAX_TIMEOUT = 7000;

  private static final int CONNECT_TIMEOUT = 10000;

  private static final int SOCKET_TIMEOUT = 40000;

  private static final String CHARSET = "UTF-8";

  public HttpClientUtils() {

  }

  public static String doGet(String url) throws Exception {

    return doGet(url, new HashMap());

  }

  public static String doGet(String url, Map params) throws Exception {

    String result = null;

    if (StringUtils.isEmpty(url)) {

      LOG.info("warn:doGet url is null or '' ");

      return result;

    } else {

      List pairList = new ArrayList(params.size());

      Iterator var4 = params.entrySet().iterator();

      while(var4.hasNext()) {

        Entry entry = (Entry)var4.next();

        NameValuePair pair = new BasicNameValuePair((String)entry.getKey(), entry.getValue().toString());

        pairList.add(pair);

      }

      CloseableHttpResponse response = null;

      InputStream instream = null;

      CloseableHttpClient httpclient = HttpClients.createDefault();

      try {

        URIBuilder URIBuilder = new URIBuilder(url);

        URIBuilder.addParameters(pairList);

        URI uri = URIBuilder.build();

        HttpGet httpGet = new HttpGet(uri);

        response = httpclient.execute(httpGet);

        int statusCode = response.getStatusLine().getStatusCode();

        LOG.info("doGet statusCode:{}", statusCode);

        HttpEntity entity = response.getEntity();

        if (entity != null) {

          instream = entity.getContent();

          result = IOUtils.toString(instream, "UTF-8");

        }

      } catch (IOException var16) {

        LOG.error("doGet IO ERROR :{}", var16.getMessage());

      } catch (URISyntaxException var17) {

        LOG.error("doGet URISyntaxException :{}", var17.getMessage());

      } finally {

        if (null != instream) {

          instream.close();

        }

        if (null != response) {

          response.close();

        }

        if (null != httpclient) {

          httpclient.close();

        }

        LOG.info("close instream response httpClient connection succ");

      }

      return result;

    }

  }

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

    String result = null;

    if (StringUtils.isEmpty(url)) {

      LOG.info("warn:doGet url is null or '' ");

      return result;

    } else {

      List pairList = new ArrayList(params.size());

      Iterator var5 = params.entrySet().iterator();

      while(var5.hasNext()) {

        Entry entry = (Entry)var5.next();

        NameValuePair pair = new BasicNameValuePair((String)entry.getKey(), entry.getValue().toString());

        pairList.add(pair);

      }

      CloseableHttpResponse response = null;

      InputStream instream = null;

      CloseableHttpClient httpclient = HttpClients.createDefault();

      try {

        URIBuilder URIBuilder = new URIBuilder(url);

        URIBuilder.addParameters(pairList);

        URI uri = URIBuilder.build();

        HttpGet httpGet = new HttpGet(uri);

        response = httpclient.execute(httpGet);

        int statusCode = response.getStatusLine().getStatusCode();

        LOG.info("doGet statusCode:{}", statusCode);

        HttpEntity entity = response.getEntity();

        if (entity != null) {

          instream = entity.getContent();

          result = IOUtils.toString(instream, charset);

        }

      } catch (IOException var17) {

        LOG.error("doGet IO ERROR :{}", var17.getMessage());

      } catch (URISyntaxException var18) {

        LOG.error("doGet URISyntaxException :{}", var18.getMessage());

      } finally {

        if (null != instream) {

          instream.close();

        }

        if (null != response) {

          response.close();

        }

        if (null != httpclient) {

          httpclient.close();

        }

        LOG.info("close instream response httpClient connection succ");

      }

      return result;

    }

  }

  public static String doPost(String apiUrl) throws Exception {

    return doPost(apiUrl, (Map)(new HashMap()));

  }

  public static String doPost(String url, Map params) throws Exception {

    String result = null;

    String param = "";

    if (StringUtils.isEmpty(url)) {

      LOG.info("warn:doPost url is null or '' ");

      return result;

    } else {

      List pairList = new ArrayList(params.size());

      Iterator var5 = params.entrySet().iterator();

      while(var5.hasNext()) {

        Entry entry = (Entry)var5.next();

        NameValuePair pair = new BasicNameValuePair((String)entry.getKey(), entry.getValue().toString());

        pairList.add(pair);

        if (param.equals("")) {

          param = (String)entry.getKey() + "=" + entry.getValue();

        } else {

          param = param + "&" + (String)entry.getKey() + "=" + entry.getValue();

        }

      }

      LOG.info("http请求地址:" + url + "?" + param);

      CloseableHttpClient httpClient = HttpClients.createDefault();

      HttpPost httpPost = new HttpPost(url);

      CloseableHttpResponse response = null;

      InputStream instream = null;

      try {

        httpPost.setConfig(requestConfig);

        httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));

        response = httpClient.execute(httpPost);

        int statusCode = response.getStatusLine().getStatusCode();

        LOG.info("doPost statusCode:{}", statusCode);

        HttpEntity entity = response.getEntity();

        if (entity != null) {

          instream = entity.getContent();

          result = IOUtils.toString(instream, "UTF-8");

          LOG.info("doPost Result:{}", result);

        }

      } catch (IOException var14) {

        LOG.error("doPost ERROR :{}", var14.getMessage());

      } finally {

        if (null != instream) {

          instream.close();

        }

        if (null != response) {

          response.close();

        }

        if (null != httpClient) {

          httpClient.close();

        }

        LOG.info("close instream response httpClient connection succ");

      }

      return result;

    }

  }

  public static String doPost(String url, String xml) throws Exception {

    String result = null;

    if (StringUtils.isEmpty(url)) {

      LOG.info("warn:doPost url is null or '' ");

      return result;

    } else {

      CloseableHttpClient httpClient = HttpClients.createDefault();

      HttpPost httpPost = new HttpPost(url);

      CloseableHttpResponse response = null;

      InputStream instream = null;

      try {

        LOG.info("短信请求服务器地址:" + url + "?" + xml);

        httpPost.setConfig(requestConfig);

        httpPost.setEntity(new StringEntity(xml, "GBK"));

        response = httpClient.execute(httpPost);

        int statusCode = response.getStatusLine().getStatusCode();

        LOG.info("doPost statusCode:{}", statusCode);

        HttpEntity entity = response.getEntity();

        if (entity != null) {

          instream = entity.getContent();

          result = IOUtils.toString(instream, "UTF-8");

        }

      } catch (IOException var12) {

        LOG.error("doPost ERROR :{}", var12.getMessage());

      } finally {

        if (null != instream) {

          instream.close();

        }

        if (null != response) {

          response.close();

        }

        if (null != httpClient) {

          httpClient.close();

        }

        LOG.info("close instream response httpClient connection succ");

      }

      return result;

    }

  }

  public static String doPost(String url, Object json) throws Exception {

    String result = null;

    if (StringUtils.isEmpty(url)) {

      LOG.info("warn:doPostByJson url is null or '' ");

      return result;

    } else {

      CloseableHttpClient httpClient = HttpClients.createDefault();

      HttpPost httpPost = new HttpPost(url);

      CloseableHttpResponse response = null;

      InputStream instream = null;

      try {

        httpPost.setConfig(requestConfig);

        StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");

        stringEntity.setContentEncoding("UTF-8");

        stringEntity.setContentType("application/json");

        httpPost.setEntity(stringEntity);

        response = httpClient.execute(httpPost);

        int statusCode = response.getStatusLine().getStatusCode();

        LOG.info("doPost statusCode:{}", statusCode);

        HttpEntity entity = response.getEntity();

        if (entity != null) {

          instream = entity.getContent();

          result = IOUtils.toString(instream, "UTF-8");

        }

      } catch (IOException var13) {

        LOG.error("doPost BY JSON ERROR :{}", var13.getMessage());

      } finally {

        if (null != instream) {

          instream.close();

        }

        if (null != response) {

          response.close();

        }

        if (null != httpClient) {

          httpClient.close();

        }

      }

      return result;

    }

  }

  public static String doPostPay(String url, Object json) throws Exception {

    String result = null;

    if (StringUtils.isEmpty(url)) {

      LOG.info("warn:doPostByJson url is null or '' ");

      return result;

    } else {

      CloseableHttpClient httpClient = HttpClients.createDefault();

      HttpPost httpPost = new HttpPost(url);

      CloseableHttpResponse response = null;

      InputStream instream = null;

      try {

        httpPost.setConfig(requestConfig);

        StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");

        httpPost.setHeader("Content-Type", "application/json;charset=utf-8");

        httpPost.setHeader("Accept", "application/json");

        stringEntity.setContentEncoding("UTF-8");

        stringEntity.setContentType("application/json");

        httpPost.setEntity(stringEntity);

        response = httpClient.execute(httpPost);

        int statusCode = response.getStatusLine().getStatusCode();

        LOG.info("doPost statusCode:{}", statusCode);

        HttpEntity entity = response.getEntity();

        if (entity != null) {

          instream = entity.getContent();

          result = IOUtils.toString(instream, "UTF-8");

        }

      } catch (IOException var13) {

        LOG.error("doPost BY JSON ERROR :{}", var13.getMessage());

      } finally {

        if (null != instream) {

          instream.close();

        }

        if (null != response) {

          response.close();

        }

        if (null != httpClient) {

          httpClient.close();

        }

      }

      return result;

    }

  }

  public static String doPostSSL(String apiUrl, Map params) throws Exception {

    String result = null;

    if (StringUtils.isEmpty(apiUrl)) {

      LOG.info("warn:doPostSSL url is null or '' ");

      return result;

    } else {

      CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();

      HttpPost httpPost = new HttpPost(apiUrl);

      CloseableHttpResponse response = null;

      InputStream instream = null;

      try {

        httpPost.setConfig(requestConfig);

        List pairList = new ArrayList(params.size());

        Iterator var8 = params.entrySet().iterator();

        Entry entry;

        while(var8.hasNext()) {

          entry = (Entry)var8.next();

          NameValuePair pair = new BasicNameValuePair((String)entry.getKey(), entry.getValue().toString());

          pairList.add(pair);

        }

        httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("utf-8")));

        response = httpClient.execute(httpPost);

        int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode != 200) {

          LOG.info("doPostSSL statusCode:{}", statusCode);

          entry = null;

          return String.valueOf(entry);

        }

        HttpEntity entity = response.getEntity();

        if (entity != null) {

          instream = entity.getContent();

          result = IOUtils.toString(instream, "UTF-8");

        }

      } catch (Exception var14) {

        LOG.error("doPostSSL ERROR :{}", var14.getMessage());

      } finally {

        if (null != instream) {

          instream.close();

        }

        if (null != response) {

          response.close();

        }

        if (null != httpClient) {

          httpClient.close();

        }

        LOG.info("close instream response httpClient connection succ");

      }

      return result;

    }

  }

  public static String doPostSSL(String apiUrl, Object json) throws Exception {

    String result = null;

    if (StringUtils.isEmpty(apiUrl)) {

      LOG.info("warn:doPostSSL By Json url is null or '' ");

      return result;

    } else {

      CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();

      HttpPost httpPost = new HttpPost(apiUrl);

      CloseableHttpResponse response = null;

      InputStream instream = null;

      HttpEntity entity;

      try {

        httpPost.setConfig(requestConfig);

        StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");

        stringEntity.setContentEncoding("UTF-8");

        stringEntity.setContentType("application/json");

        httpPost.setEntity(stringEntity);

        response = httpClient.execute(httpPost);

        int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode == 200) {

          entity = response.getEntity();

          if (entity != null) {

            instream = entity.getContent();

            result = IOUtils.toString(instream, "UTF-8");

          }

          return result;

        }

        LOG.info("doPostSSL by json statusCode:{}", statusCode);

        entity = null;

      } catch (Exception var13) {

        LOG.error("doPostSSL BY JSON ERROR :{}", var13.getMessage());

        return result;

      } finally {

        if (null != instream) {

          instream.close();

        }

        if (null != response) {

          response.close();

        }

        if (null != httpClient) {

          httpClient.close();

        }

        LOG.info("close instream response httpClient connection succ");

      }

      return String.valueOf(entity);

    }

  }

  private static SSLConnectionSocketFactory createSSLConnSocketFactory() {

    SSLConnectionSocketFactory sslsf = null;

    try {

      SSLContext sslContext = (new SSLContextBuilder()).loadTrustMaterial((KeyStore)null, new TrustStrategy() {

        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {

          return true;

        }

      }).build();

      sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {

        public boolean verify(String arg0, SSLSession arg1) {

          return true;

        }

        public void verify(String host, SSLSocket ssl) throws IOException {

        }

        public void verify(String host, X509Certificate cert) throws SSLException {

        }

        public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {

        }

      });

    } catch (GeneralSecurityException var2) {

      LOG.error("createSSLConnSocketFactory ERROR :{}", var2.getMessage());

    }

    return sslsf;

  }

  public static String doPostPay(String url, Object json, String authorization) throws Exception {

    String result = null;

    if (StringUtils.isEmpty(url)) {

      LOG.info("warn:doPostByJson url is null or '' ");

      return result;

    } else {

      CloseableHttpClient httpClient = HttpClients.createDefault();

      HttpPost httpPost = new HttpPost(url);

      CloseableHttpResponse response = null;

      InputStream instream = null;

      try {

        httpPost.setConfig(requestConfig);

        StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");

        httpPost.setHeader("Content-Type", "application/json;charset=utf-8");

        httpPost.setHeader("Accept", "application/json");

        httpPost.setHeader("Authorization", authorization);

        stringEntity.setContentEncoding("UTF-8");

        stringEntity.setContentType("application/json");

        httpPost.setEntity(stringEntity);

        response = httpClient.execute(httpPost);

        int statusCode = response.getStatusLine().getStatusCode();

        LOG.info("doPost statusCode:{}", statusCode);

        HttpEntity entity = response.getEntity();

        if (entity != null) {

          instream = entity.getContent();

          result = IOUtils.toString(instream, "UTF-8");

        }

      } catch (IOException var14) {

        LOG.error("doPost BY JSON ERROR :{}", var14.getMessage());

      } finally {

        if (null != instream) {

          instream.close();

        }

        if (null != response) {

          response.close();

        }

        if (null != httpClient) {

          httpClient.close();

        }

      }

      return result;

    }

  }

  public static String doPostPayUpgraded(String url, Object json, String authorization) throws Exception {

    String result = null;

    if (StringUtils.isEmpty(url)) {

      LOG.info("新支付接口url不能为空!");

      return result;

    } else {

      CloseableHttpClient httpClient = HttpClients.createDefault();

      HttpPost httpPost = new HttpPost(url);

      CloseableHttpResponse response = null;

      InputStream instream = null;

      try {

        httpPost.setConfig(requestConfig);

        StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");

        httpPost.setHeader("Accept", "application/json");

        httpPost.setHeader("Content-Type", "application/json;charset=utf-8");

        httpPost.setHeader("Authorization", authorization);

        stringEntity.setContentEncoding("UTF-8");

        stringEntity.setContentType("application/json");

        httpPost.setEntity(stringEntity);

        response = httpClient.execute(httpPost);

        int statusCode = response.getStatusLine().getStatusCode();

        LOG.info("新支付请求状态 statusCode:{}", statusCode);

        HttpEntity entity = response.getEntity();

        if (entity != null) {

          instream = entity.getContent();

          result = IOUtils.toString(instream, "UTF-8");

        }

      } catch (IOException var14) {

        LOG.error("新支付接口发送异常:{}", var14.getMessage());

      } finally {

        if (null != instream) {

          instream.close();

        }

        if (null != response) {

          response.close();

        }

        if (null != httpClient) {

          httpClient.close();

        }

      }

      return result;

    }

  }

  static {

    connMgr.setMaxTotal(100);

    connMgr.setDefaultMaxPerRoute(100);

    Builder configBuilder = RequestConfig.custom();

    configBuilder.setConnectTimeout(10000);

    configBuilder.setSocketTimeout(40000);

    configBuilder.setConnectionRequestTimeout(7000);

    configBuilder.setStaleConnectionCheckEnabled(true);

    requestConfig = configBuilder.build();

  }

}

HttpClientUtils

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,732评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,496评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,264评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,807评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,806评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,675评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,029评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,683评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 41,704评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,666评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,773评论 1 332
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,413评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,016评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,978评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,204评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,083评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,503评论 2 343

推荐阅读更多精彩内容