Java HttpClientUtil

package com.bestpay.bank.agreement.common.utils;

import static com.google.common.base.Preconditions.checkArgument;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Map;

import javax.net.ssl.*;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
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.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import com.bestpay.bank.agreement.common.exception.ProcessException;
import com.bestpay.bank.agreement.common.exception.RCManager;
import com.google.common.base.Objects;
import com.google.common.collect.Lists;

/**

  • User: zhangleimin

  • Date: 13-12-6

  • Time: 上午11:28
    */
    @Slf4j
    public class HttpClientUtil {

    private static RequestConfig config;

    private static HttpClientUtil httpClientUtil;

    private HttpClientUtil() {
    }

    /**

    • https协议加密
      */
      private static class TrustAnyTrustManager implements X509TrustManager {

      @Override
      public void checkClientTrusted(X509Certificate[] chain, String authType)
      throws CertificateException {
      }

      @Override
      public void checkServerTrusted(X509Certificate[] chain, String authType)
      throws CertificateException {
      }

      @Override
      public X509Certificate[] getAcceptedIssuers() {
      return new X509Certificate[] {};
      }
      }

    private static class TrustAnyHostnameVerifier implements HostnameVerifier {
    @Override
    public boolean verify(String hostname, SSLSession session) {
    return true;
    }
    }

    public static HttpClientUtil createHttpClientUtil(int connTimeout, int reqTimeout) {
    config = RequestConfig.custom().setConnectTimeout(connTimeout).setSocketTimeout(reqTimeout)
    .build();
    httpClientUtil = new HttpClientUtil();
    return httpClientUtil;
    }

    public static HttpClientUtil createHttpClientUtil(int connTimeout, int reqTimeout,
    String proxyHost, int proxyPort) {
    config = RequestConfig.custom().setConnectTimeout(connTimeout).setSocketTimeout(reqTimeout)
    .setProxy(new HttpHost(proxyHost, proxyPort)).setAuthenticationEnabled(true).build();
    httpClientUtil = new HttpClientUtil();
    return httpClientUtil;
    }

    public static HttpClientUtil createHttpClientUtil() {
    config = RequestConfig.custom().setConnectTimeout(0).setSocketTimeout(0).build();
    httpClientUtil = new HttpClientUtil();
    return httpClientUtil;
    }

    public static String sendByPost(String url, Map<String, String> param) throws Exception {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = null;
    CloseableHttpResponse response = null;
    try {
    httpPost = new HttpPost(url);
    List paraList = Lists.newArrayList();
    for (String key : param.keySet()) {
    paraList.add(new BasicNameValuePair(key, param.get(key)));
    }
    httpPost.setEntity(new UrlEncodedFormEntity(paraList, Consts.UTF_8));
    httpPost.setConfig(config);
    response = httpClient.execute(httpPost);
    HttpEntity entity = response.getEntity();
    int statusCode = response.getStatusLine().getStatusCode();
    checkArgument(Objects.equal(statusCode, HttpStatus.SC_OK), “响应码状态不是200”);
    return EntityUtils.toString(entity);
    } finally {
    httpClient.close();
    if (response != null) {
    response.close();
    }
    if (httpPost != null) {
    httpPost.releaseConnection();
    }

     }
    

    }

    public static String sendByGet(String url, Map<String, String> param) {
    CloseableHttpClient httpClient = null;
    try {
    httpClient = HttpClients.createDefault();
    StringBuffer paramUrl = new StringBuffer();
    for (String key : param.keySet()) {
    paramUrl.append("&").append(key).append("=").append(param.get(key));
    }
    HttpGet httpGet = new HttpGet(url + paramUrl);
    httpGet.setConfig(config);
    HttpResponse response = httpClient.execute(httpGet);
    HttpEntity entity = response.getEntity();
    int statusCode = response.getStatusLine().getStatusCode();
    checkArgument(Objects.equal(statusCode, HttpStatus.SC_OK), “响应码状态不是200”);
    return EntityUtils.toString(entity);
    } catch (Exception e) {
    log.error(“调用HTTP服务异常”, e);
    return “”;
    } finally {
    if (httpClient != null) {
    try {
    httpClient.close();
    } catch (IOException ex) {
    log.error(“关闭httpClient出现异常IOException:”, ex);
    }
    }
    }
    }

    /**

    • 执行后台Http请求

    • @param reqUrl 请求URl

    • @param params 请求参数

    • @return
      */
      public static String invokeRequest(String reqUrl, String params) {
      CloseableHttpClient httpClient = HttpClients.createDefault();
      HttpPost httpPost = new HttpPost(reqUrl);
      try {
      httpPost.setEntity(new StringEntity(params, “GBK”));
      HttpResponse response = httpClient.execute(httpPost);
      HttpEntity entity = response.getEntity();

       String value = EntityUtils.toString(entity, "GBK");
       EntityUtils.consume(entity);
       return value;
      

      } catch (Exception e) {
      log.error(“http请求异常”, e);
      return StringUtils.EMPTY;
      } finally {
      try {
      httpClient.close();
      } catch (IOException ex) {
      log.error(“关闭httpClient出现异常IOException:”, ex);
      }
      }
      }

    /**

    • 执行后台Http请求

    • @param reqUrl 请求URl

    • @param params 请求参数

    • @param encode 请求编码 UTF-8 ,GBK

    • @return
      */
      public static String invokeRequest(String reqUrl, String params, String encode) {
      CloseableHttpClient httpClient = HttpClients.createDefault();
      HttpPost httpPost = new HttpPost(reqUrl);
      try {
      httpPost.setEntity(new StringEntity(params, encode));
      HttpResponse response = httpClient.execute(httpPost);
      HttpEntity entity = response.getEntity();

       String value = EntityUtils.toString(entity, encode);
       EntityUtils.consume(entity);
       return value;
      

      } catch (Exception e) {
      log.error(“http请求异常”, e);
      return StringUtils.EMPTY;
      } finally {
      try {
      httpClient.close();
      } catch (IOException ex) {
      log.error(“关闭httpClient出现异常IOException:”, ex);
      }
      }
      }

    private static void registerSSl(org.apache.http.client.HttpClient httpclient) throws Exception {
    SSLContext sslcontext = SSLContext.getInstance(“TLS”);
    X509TrustManager tm = new X509TrustManager() {
    @Override
    public void checkClientTrusted(X509Certificate[] arg0,
    String arg1) throws CertificateException {
    }

         @Override
         public void checkServerTrusted(X509Certificate[] arg0,
                                        String arg1) throws CertificateException {
         }
    
         @Override
         public X509Certificate[] getAcceptedIssuers() {
             return null;
         }
     };
     sslcontext.init(null, new TrustManager[] { tm }, null);
     SSLSocketFactory sf = new SSLSocketFactory(sslcontext,
         SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
     Scheme https = new Scheme("https", 443, sf);
     httpclient.getConnectionManager().getSchemeRegistry().register(https);
    

    }

    /**

    • http请求json格式的报文
    • @param url 地址
    • @param json http请求json格式
    • @return 返回json格式报文
      */
      public static String invokeHttpPostJson(String url, String json) {
      log.info(“付款码HTTP验证请求参数:{}”, json);
      CloseableHttpClient httpClient = HttpClients.createDefault();
      HttpPost method = new HttpPost(url);
      method.setConfig(config);
      try {
      StringEntity entity = new StringEntity(json, “utf-8”);
      entity.setContentEncoding(“UTF-8”);
      entity.setContentType(“application/json”);
      method.setEntity(entity);
      HttpResponse result = httpClient.execute(method);
      if (result.getStatusLine().getStatusCode() != 200) {
      log.info(“付款码HTTP验证响应异常,HTTP状态码{}”, result.getStatusLine().getStatusCode());
      return StringUtils.EMPTY;
      }
      // 请求结束,返回结果
      String resData = EntityUtils.toString(result.getEntity());
      log.info(“付款码HTTP验证响应结果:{}”, resData);
      return resData;
      } catch (Exception e) {
      log.error(“付款码HTTP验证出错, URL:{},异常:”, url, e);
      throw new ProcessException(RCManager.BM999996.getCode(), RCManager.BM999996.getDesc());
      } finally {
      try {
      httpClient.close();
      } catch (Exception e) {
      log.error(“HTTP连接关闭失败, URL:{}”, url, e);
      }
      }
      }

    public static String invokeRequestForCeb(String reqUrl, String params) {
    HttpPost httpPost = null;
    try {
    HttpParams param = new BasicHttpParams();
    param.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20000); // 连接超时
    param.setParameter(CoreConnectionPNames.SO_TIMEOUT, 50000); // 请求超时
    org.apache.http.client.HttpClient httpclient = new DefaultHttpClient(param);
    registerSSl(httpclient);
    httpPost = new HttpPost(reqUrl);
    httpPost.setEntity(new StringEntity(params, “UTF-8”));
    HttpResponse response = httpclient.execute(httpPost);
    HttpEntity entity = response.getEntity();
    String value = EntityUtils.toString(entity, “UTF-8”);
    EntityUtils.consume(entity);
    return value;
    } catch (Exception e) {
    log.error(“执行http请求异常: {}”, e);
    return StringUtils.EMPTY;
    } finally {
    httpPost = null;
    log.debug(“结束http请求…”);
    }
    }

    /**

    • http请求post
    • Author:xiaofabing
    • @param url
    • @param param
    • @return
    • @throws Exception
      */
      public String sendByPost(String url, String param) throws Exception {
      CloseableHttpClient httpClient = HttpClients.createDefault();
      HttpPost httpPost = null;
      CloseableHttpResponse response = null;
      try {
      httpPost = new HttpPost(url);
      httpPost.setEntity(new StringEntity(param, Consts.UTF_8));
      httpPost.setConfig(config);
      response = httpClient.execute(httpPost);
      HttpEntity entity = response.getEntity();
      int statusCode = response.getStatusLine().getStatusCode();
      checkArgument(Objects.equal(statusCode, HttpStatus.SC_OK), “响应码状态不是200”);
      return EntityUtils.toString(entity, Consts.UTF_8);
      } finally {
      httpClient.close();
      if (response != null) {
      response.close();
      }
      if (httpPost != null) {
      httpPost.releaseConnection();
      }
      }
      }

    /**

    • http请求post
    • Author:孟凡霄
    • @param url
    • @param param1
    • @return
    • @throws Exception
      */
      public String sendByPostForURB(String url, String param1) throws Exception {
      HttpPost httpPost = null;
      try {
      HttpParams param = new BasicHttpParams();
      param.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 2000); // 连接超时
      param.setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000); // 请求超时
      HttpClient httpclient = new DefaultHttpClient(param);
      registerSSl(httpclient);
      httpPost = new HttpPost(url);
      httpPost.setEntity(new StringEntity(param1, “UTF-8”));
      HttpResponse response = httpclient.execute(httpPost);
      HttpEntity entity = response.getEntity();
      String value = EntityUtils.toString(entity, “UTF-8”);
      EntityUtils.consume(entity);
      return value;
      } catch (Exception e) {
      log.error("【农信之杭州联合银行快捷借】执行http请求异常: “, e);
      throw new Exception(”【农信之杭州联合银行快捷借】执行http请求异常");
      } finally {
      if (httpPost != null) {
      httpPost.releaseConnection();
      }
      }
      }

    /**

    • 以post的方式发送数据,并可以指定发送内容的类型
    • @param url 服务端地址
    • @param param 请求参数
    • @param contentType 发送内容的类型
    • @return
    • @throws Exception
      */
      public String sendByPost(String url, String param, ContentType contentType) throws Exception {
      CloseableHttpClient httpClient = HttpClients.createDefault();
      HttpPost httpPost = null;
      CloseableHttpResponse response = null;
      try {
      httpPost = new HttpPost(url);
      httpPost.setEntity(new StringEntity(param, contentType));
      httpPost.setConfig(config);
      response = httpClient.execute(httpPost);
      HttpEntity entity = response.getEntity();
      int statusCode = response.getStatusLine().getStatusCode();
      checkArgument(Objects.equal(statusCode, HttpStatus.SC_OK),
      “响应码状态不是200, 响应码状态:” + statusCode);
      return EntityUtils.toString(entity, Consts.UTF_8);
      } finally {
      httpClient.close();
      if (response != null) {
      response.close();
      }
      if (httpPost != null) {
      httpPost.releaseConnection();
      }
      }
      }

    /**

    • 执行后台Http请求

    • @param reqUrl 请求URl

    • @param params 请求参数

    • @param contentType

    • @param sslFlg 是否需要ssl加密

    • @return
      */
      public static String invokeRequest(String reqUrl, String params, boolean sslFlg,
      ContentType contentType) {

      CloseableHttpClient httpClient = new DefaultHttpClient();
      if (sslFlg) {
      try {
      registerSSl(httpClient);
      } catch (NoSuchAlgorithmException e) {
      log.error(“注册SSL失败”, e);
      } catch (KeyManagementException e) {
      log.error(“注册SSL失败”, e);
      } catch (Exception e) {
      e.printStackTrace();
      }
      }

      HttpPost httpPost = new HttpPost(reqUrl);

      try {
      httpPost.setEntity(new StringEntity(params, contentType));
      HttpResponse response = httpClient.execute(httpPost);
      HttpEntity entity = response.getEntity();

       String value = EntityUtils.toString(entity, contentType.getCharset());
       EntityUtils.consume(entity);
       return value;
      

      } catch (Exception e) {
      log.error(“http请求异常”, e);
      return StringUtils.EMPTY;
      } finally {
      if(httpClient != null){
      try {
      httpClient.close();
      } catch (IOException e) {
      e.printStackTrace();
      }
      }
      }
      }
      /**

    • post方式请求服务器(https协议)

    • @param url

    •        请求地址
      
    • @param content

    •        参数
      
    • @param charset

    •        编码
      
    • @return

    • @throws NoSuchAlgorithmException

    • @throws KeyManagementException

    • @throws IOException
      */
      public static byte[] httpsRequest(String url, String content, String charset)
      throws NoSuchAlgorithmException, KeyManagementException,
      IOException {
      log.info(“https地址:{},编码格式:{}”, url, charset);
      SSLContext sc = SSLContext.getInstance(“SSL”);
      sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },
      new SecureRandom());

      URL console = new URL(url);
      HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
      conn.setSSLSocketFactory(sc.getSocketFactory());
      conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
      conn.setDoOutput(true);
      conn.setConnectTimeout(8000);
      conn.connect();

      DataOutputStream out = new DataOutputStream(conn.getOutputStream());
      out.write(content.getBytes(charset));
      // 刷新、关闭
      out.flush();
      out.close();
      InputStream is = conn.getInputStream();
      if (is != null) {
      ByteArrayOutputStream outStream = new ByteArrayOutputStream();
      byte[] buffer = new byte[1024];
      int len = 0;
      while ((len = is.read(buffer)) != -1) {
      outStream.write(buffer, 0, len);
      }
      is.close();
      return outStream.toByteArray();
      }
      return null;
      }

    /**

    • 执行后台Http请求

    • @param reqUrl 请求URl

    • @param params 请求参数

    • @param contentType

    • @param sslFlg 是否需要ssl加密

    • @return
      */
      public String invokeRequest(String reqUrl, String params, boolean sslFlg,
      ContentType contentType, String Spare) {

      CloseableHttpClient httpClient = new DefaultHttpClient();
      if (sslFlg) {
      try {
      registerSSll(httpClient);
      } catch (NoSuchAlgorithmException e) {
      log.error(“注册SSL失败”, e);
      } catch (KeyManagementException e) {
      log.error(“注册SSL失败”, e);
      }
      }

      HttpPost httpPost = new HttpPost(reqUrl);
      CloseableHttpResponse response = null;
      try {
      httpPost.setConfig(config);
      httpPost.setEntity(new StringEntity(params, contentType));
      response = httpClient.execute(httpPost);
      HttpEntity entity = response.getEntity();

       String value = EntityUtils.toString(entity, contentType.getCharset());
       EntityUtils.consume(entity);
       return value;
      

      } catch (Exception e) {
      log.error(“http请求异常”, e);
      return StringUtils.EMPTY;
      } finally {
      if (response != null) {
      try {
      response.close();
      } catch (IOException e) {
      log.error(“response IOException”, e);
      }
      }
      if (httpPost != null) {
      httpPost.releaseConnection();
      }
      if (httpClient != null) {
      try {
      httpClient.close();
      } catch (IOException e) {
      log.error(“httpClient IOException”, e);
      }
      }
      }
      }

    private static void registerSSll(HttpClient httpclient) throws NoSuchAlgorithmException,
    KeyManagementException {
    SSLContext sslcontext = SSLContext.getInstance(“SSL”);
    X509TrustManager tm = new X509TrustManager() {
    @Override
    public void checkClientTrusted(X509Certificate[] arg0, String arg1)
    throws CertificateException {
    }

         @Override
         public void checkServerTrusted(X509Certificate[] arg0, String arg1)
                 throws CertificateException {
         }
    
         @Override
         public X509Certificate[] getAcceptedIssuers() {
             return null;
         }
     };
     sslcontext.init(null, new TrustManager[]{tm}, null);
     SSLSocketFactory sf = new SSLSocketFactory(sslcontext,
             SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
     Scheme https = new Scheme("https", 443, sf);
     httpclient.getConnectionManager().getSchemeRegistry().register(https);
    

    }
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值