HttpClientUtil 封装方法

package com.cat.common.http;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.net.ssl.SSLContext;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import com.cat.common.bean.EMsg;
import com.cat.common.exception.RequestException;
import com.cat.common.lang.RString;

@Service("httpClientUtil")
public class HttpClientUtil{

   /** 
    * 连接超时时间
    */
   private static int CONNECT_TIMEOUT = 10 * 1000;

   /** 
    * 短时间连接超时时间
    */
   private static int SHORT_TIMEOUT = 5 * 1000;

   /**
    * 套接字超时时间
    */
   private static int SOCKET_TIMEOUT = 35 * 1000;

   /**
    * 连接池中 连接请求执行被阻塞的超时时间
    */

   private static int CONN_MANAGER_TIMEOUT = 10 * 1000;

   private CloseableHttpClient getHttpClient(boolean isShortTime){
      int ctime = CONNECT_TIMEOUT;
      int stime = SOCKET_TIMEOUT;
      int cmtime = CONN_MANAGER_TIMEOUT;
      if(isShortTime){
         //短时间快速响应
         ctime = SHORT_TIMEOUT;
         stime = SHORT_TIMEOUT;
         cmtime = SHORT_TIMEOUT;
      }
      RequestConfig requestConfig = RequestConfig.custom()
      //设置连接到第三方服务的超时时间
            .setConnectTimeout(ctime)
            //设置第三方服务传输数据的超时时间
            .setSocketTimeout(stime)
            //设置从连接池获取连接超时时间
            .setConnectionRequestTimeout(cmtime).build();
      //设置重定向策略      //为大连接量考虑,设置重试次数为0,默认为3
      CloseableHttpClient httpclient = HttpClients.custom().setRetryHandler(new DefaultHttpRequestRetryHandler(0, false)).setDefaultRequestConfig(requestConfig).build();
      return httpclient;
   }

   public String postHttplientJson(String url,
                                   String info)
         throws RequestException{
      return postJson(url, info, false);
   }

   /**
    * 增加header头
    * @param url
    * @param info
    * @param header
    * @return
    * @throws RequestException 
    */
   public String postHttplientJsonHeard(String url,
                                        String info,
                                        Map<String, String> header)
         throws RequestException{
      return postJson(url, info, false, header, "");
   }

   /**
    * 短时间快速响应,不然就超时断开,默认5秒
    * @param url
    * @param info
    * @return
    * @throws RequestException 
    */
   public String postHttplientJsonShortTime(String url,
                                            String info)
         throws RequestException{
      return postJson(url, info, true);
   }

   public String postJson(String url,
                          String info,
                          boolean isShortTime)
         throws RequestException{
      return postJson(url, info, isShortTime, null, "");
   }

   public String postJson(String url,
                          String info,
                          boolean isShortTime,
                          Map<String, String> headers,
                          String contentType)
         throws RequestException{
      CloseableHttpResponse resp = null;
      InputStream instream = null;
      BufferedReader reader = null;
      CloseableHttpClient httpclient = null;
      try{
         httpclient = getHttpClient(isShortTime);
         HttpPost httpPost = new HttpPost(url);
         StringEntity sentity = new StringEntity(info, "utf-8");// 解决中文乱码问题
         if(RString.isNotBlank(info)){
            httpPost.setEntity(sentity);
         }
         httpPost.setHeader("ContentType", "text/plain; charset=UTF-8");
         sentity.setContentType("application/json;charset=UTF-8");
         if(RString.isNotBlank(contentType)){
            httpPost.setHeader("ContentType", contentType);
            sentity.setContentType(contentType);
         }
         if(headers != null){
            for(Entry<String, String> entry : headers.entrySet()){
               Header header = new BasicHeader(entry.getKey(), entry.getValue());
               httpPost.addHeader(header);
            }
         }

         resp = httpclient.execute(httpPost);

         HttpEntity entity = resp.getEntity();
         if(entity == null){
            return "";
         }
         instream = entity.getContent();
         reader = new BufferedReader(new InputStreamReader(instream, "utf-8"));
         StringBuffer stringBuffer = new StringBuffer();
         String str = "";
         while((str = reader.readLine()) != null){
            stringBuffer.append(str);
         }
         return stringBuffer.toString();
      }catch(ClientProtocolException e){
         e.printStackTrace();
         throw new RequestException(EMsg.Http_Client_Error.code(), EMsg.Http_Client_Error.value(), e);
      }catch(IOException e){
         e.printStackTrace();
         throw new RequestException(EMsg.Http_Io_Error.code(), EMsg.Http_Io_Error.value(), e);
      }finally{
         try{
            httpclient.close();
            resp.close();
            instream.close();
            reader.close();
         }catch(Exception e){
            e.printStackTrace();
         }
      }
   }

   public String get(String url,
                     boolean isShortTime)
         throws RequestException{
      CloseableHttpResponse resp = null;
      InputStream instream = null;
      BufferedReader reader = null;
      CloseableHttpClient httpclient = null;
      try{
         httpclient = getHttpClient(isShortTime);
         HttpGet httpGet = new HttpGet(url);
         resp = httpclient.execute(httpGet);
         HttpEntity entity = resp.getEntity();
         if(entity == null){
            return "";
         }
         instream = entity.getContent();
         reader = new BufferedReader(new InputStreamReader(instream, "utf-8"));
         StringBuffer stringBuffer = new StringBuffer();
         String str = "";
         while((str = reader.readLine()) != null){
            stringBuffer.append(str);
         }
         return stringBuffer.toString();

      }catch(ClientProtocolException e){
         e.printStackTrace();
         throw new RequestException(EMsg.Http_Client_Error.code(), EMsg.Http_Client_Error.value(), e);
      }catch(IOException e){
         e.printStackTrace();
         throw new RequestException(EMsg.Http_Io_Error.code(), EMsg.Http_Io_Error.value(), e);
      }finally{
         try{
            httpclient.close();
            resp.close();
            instream.close();
            reader.close();
         }catch(Exception e){
            e.printStackTrace();
         }
      }
   }

   /**
    * 需要加密执行的
    * 
    * @param url
    * @param xmlInfo
    * @return
    * @throws RequestException 
    * @throws Exception
    */
   public String postHttplientNeedSSL(String url,
                                      String xmlInfo,
                                      String cretPath,
                                      String mrchId)
         throws RequestException{
      FileInputStream instream = null;
      CloseableHttpResponse response = null;
      CloseableHttpClient httpclient = null;
      // 选择初始化密钥文件格式
      try{
         KeyStore keyStore = KeyStore.getInstance("PKCS12");
         // 得到密钥文件流
         instream = new FileInputStream(new File(cretPath));
         // 用商户的ID 来解读文件
         keyStore.load(instream, mrchId.toCharArray());

         // 用商户的ID 来加载
         SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, mrchId.toCharArray()).build();
         // Allow TLSv1 protocol only
         SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
         // 用最新的httpclient 加载密钥
         httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
         StringBuffer ret = new StringBuffer();
         HttpPost httpPost = new HttpPost(url);
         httpPost.setEntity(new StringEntity(xmlInfo));
         response = httpclient.execute(httpPost);
         HttpEntity entity = response.getEntity();
         if(entity != null){
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
            String text;
            while((text = bufferedReader.readLine()) != null){
               ret.append(text);
            }
         }
         EntityUtils.consume(entity);

         return ret.toString();
      }catch(KeyStoreException | FileNotFoundException | CertificateException | NoSuchAlgorithmException | KeyManagementException | UnrecoverableKeyException e){
         e.printStackTrace();
         throw new RequestException(EMsg.Http_Client_Error.code(), EMsg.Http_Client_Error.value(), e);
      }catch(IOException e){
         e.printStackTrace();
         throw new RequestException(EMsg.Http_Client_Error.code(), EMsg.Http_Client_Error.value(), e);
      }finally{
         try{
            httpclient.close();
            response.close();
            instream.close();
         }catch(Exception e){
            e.printStackTrace();
         }
      }
   }

   public String postMap(String url,
                         Map<String, String> headers,
                         Map<String, String> params) throws RequestException{

      return postMap(url, false, headers, params);
   }

   /**
    * 参数为 key-value
    * @param url
    * @param isShortTime
    * @param headers
    * @param params
    * @return
    * @throws RequestException 
    */
   public String postMap(String url,
                         boolean isShortTime,
                         Map<String, String> headers,
                         Map<String, String> params)
         throws RequestException{
      CloseableHttpResponse resp = null;
      InputStream instream = null;
      BufferedReader reader = null;
      CloseableHttpClient httpclient = null;
      try{
         httpclient = getHttpClient(isShortTime);
         HttpPost httpPost = new HttpPost(url);
         httpPost.setHeader("ContentType", "text/plain; charset=UTF-8");
         if(headers != null){
            for(Entry<String, String> entry : headers.entrySet()){
               Header header = new BasicHeader(entry.getKey(), entry.getValue());
               httpPost.addHeader(header);
            }
         }
         //装填参数
         List<NameValuePair> nvps = new ArrayList<NameValuePair>();
         if(params != null){
            for(String key : params.keySet()){
               nvps.add(new BasicNameValuePair(key, params.get(key)));
            }
         }
         //设置参数到请求对象中  
         httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
         resp = httpclient.execute(httpPost);
         HttpEntity entity = resp.getEntity();
         if(entity == null){
            return "";
         }
         instream = entity.getContent();
         reader = new BufferedReader(new InputStreamReader(instream, "utf-8"));
         StringBuffer stringBuffer = new StringBuffer();
         String str = "";
         while((str = reader.readLine()) != null){
            stringBuffer.append(str);
         }
         return stringBuffer.toString();
      }catch(ClientProtocolException e){
         e.printStackTrace();
         throw new RequestException(EMsg.Http_Client_Error.code(), EMsg.Http_Client_Error.value(), e);
      }catch(IOException e){
         e.printStackTrace();
         throw new RequestException(EMsg.Http_Io_Error.code(), EMsg.Http_Io_Error.value(), e);
      }finally{
         try{
            httpclient.close();
            resp.close();
            instream.close();
            reader.close();
         }catch(Exception e){
            e.printStackTrace();
         }
      }
   }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值