基于HttpClient接口开发实例(三)

本文介绍了如何基于HttpClient封装常用请求方法,包括同步和异步请求。通过示例代码展示了HttpAsyncClient、HttpClientFactory等类的实现,适用于性能优化场景。然而,对于需要SSL证书认证的HTTP请求,当前封装可能不适用,后续章节将探讨如何处理此类情况。
摘要由CSDN通过智能技术生成

前言


在上一节中我们学习了如何生成X509-P7-DER秘钥对,并使用它们用于加签和解签。本节我将学习一下如何封装一些常用的HttpClient 方法。


概述

新建Maven项目,编写一些封装代码,为了展示方便我变一次性展示写好的代码

  • 目录
    这里写图片描述

  • 代码

    • AsyncHttpClientCallback.java

      package Util.HttpClientUtil;
      
      import org.apache.http.HttpEntity;
      import org.apache.http.HttpResponse;
      import org.apache.http.ParseException;
      import org.apache.http.client.utils.HttpClientUtils;
      import org.apache.http.concurrent.FutureCallback;
      import org.apache.http.util.EntityUtils;
      import org.slf4j.Logger;
      import org.slf4j.LoggerFactory;
      
      import java.io.IOException;
      
      /**
       * 被回调的对象,给异步的httpclient使用
       *
       */
      public class AsyncHttpClientCallback implements FutureCallback<HttpResponse> {
             
          private static Logger LOG = LoggerFactory.getLogger(AsyncHttpClientCallback.class);
      
          /**
           * 请求完成后调用该函数
           */
          @Override
          public void completed(HttpResponse response) {
      
              LOG.warn("status:{}", response.getStatusLine().getStatusCode());
              LOG.warn("response:{}", getHttpContent(response));
      
              HttpClientUtils.closeQuietly(response);
          }
      
          /**
           * 请求取消后调用该函数
           */
          @Override
          public void cancelled() {
      
          }
      
          /**
           * 请求失败后调用该函数
           */
          @Override
          public void failed(Exception e) {
      
          }
      
          protected String getHttpContent(HttpResponse response) {
      
              HttpEntity entity = response.getEntity();
              String body = null;
      
              if (entity == null) {
                  return null;
              }
      
              try {
      
                  body = EntityUtils.toString(entity, "utf-8");
      
              } catch (ParseException e) {
      
                  LOG.warn("the response's content inputstream is corrupt", e);
              } catch (IOException e) {
      
                  LOG.warn("the response's content inputstream is corrupt", e);
              }
              return body;
          }
      }
      
    • HttpAsyncClient.java

      package Util.HttpClientUtil;
      
      import org.apache.http.Consts;
      import org.apache.http.HttpHost;
      import org.apache.http.auth.AuthSchemeProvider;
      import org.apache.http.auth.AuthScope;
      import org.apache.http.auth.MalformedChallengeException;
      import org.apache.http.auth.UsernamePasswordCredentials;
      import org.apache.http.client.CredentialsProvider;
      import org.apache.http.client.config.AuthSchemes;
      import org.apache.http.client.config.RequestConfig;
      import org.apache.http.config.ConnectionConfig;
      import org.apache.http.config.Lookup;
      import org.apache.http.config.Registry;
      import org.apache.http.config.RegistryBuilder;
      import org.apache.http.conn.ssl.SSLContexts;
      import org.apache.http.impl.auth.*;
      import org.apache.http.impl.client.BasicCookieStore;
      import org.apache.http.impl.client.BasicCredentialsProvider;
      import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
      import org.apache.http.impl.nio.client.HttpAsyncClients;
      import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager;
      import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
      import org.apache.http.impl.nio.reactor.IOReactorConfig;
      import org.apache.http.nio.conn.NoopIOSessionStrategy;
      import org.apache.http.nio.conn.SchemeIOSessionStrategy;
      import org.apache.http.nio.conn.ssl.SSLIOSessionStrategy;
      import org.apache.http.nio.reactor.ConnectingIOReactor;
      import org.apache.http.nio.reactor.IOReactorException;
      
      import javax.net.ssl.SSLContext;
      import java.nio.charset.CodingErrorAction;
      import java.security.KeyManagementException;
      import java.security.KeyStoreException;
      import java.security.NoSuchAlgorithmException;
      import java.security.UnrecoverableKeyException;
      
      /**
       * 异步的HTTP请求对象,可设置代理
       */
      public class HttpAsyncClient {
      
          private static int socketTimeout = 1000;// 设置等待数据超时时间5秒钟 根据业务调整
      
          private static int connectTimeout = 2000;// 连接超时
      
          private static int poolSize = 3000;// 连接池最大连接数
      
          private static int maxPerRoute = 1500;// 每个主机的并发最多只有1500
      
          private static int connectionRequestTimeout = 3000; // 从连接池中后去连接的timeout时间
      
          // http代理相关参数
          private String host = "";
          private int port = 0;
          private String username = "";
          private String password = "";
      
          // 异步httpclient
          private CloseableHttpAsyncClient asyncHttpClient;
      
          // 异步加代理的httpclient
          private CloseableHttpAsyncClient proxyAsyncHttpClient;
      
          public HttpAsyncClient() {
              try {
                  this.asyncHttpClient = createAsyncClient(false);
                  this.proxyAsyncHttpClient = createAsyncClient(true);
              } catch (Exception e) {
                  e.printStackTrace();
              }
      
          }
      
          public CloseableHttpAsyncClient createAsyncClient(boolean proxy)
                  throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException,
                  MalformedChallengeException, IOReactorException {
      
              RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(connectionRequestTimeout)
                      .setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).build();
      
              SSLContext sslcontext = SSLContexts.createDefault();
      
              UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
      
              CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
              credentialsProvider.setCredentials(AuthScope.ANY, credentials);
      
              // 设置协议http和https对应的处理socket链接工厂的对象
              Registry<SchemeIOSessionStrategy> sessionStrategyRegistry = RegistryBuilder.<SchemeIOSessionStrategy>create()
                      .register("http", NoopIOSessionStrategy.INSTANCE)
                      .register("https", new SSLIOSessionStrategy(sslcontext)).build();
      
              // 配置io线程
              IOReactorConfig ioReactorConfig = IOReactorConfig.custom().setSoKeepAlive(false).setTcpNoDelay(true)
                      .setIoThreadCount(Runtime.getRuntime().availableProcessors()).build();
              // 设置连接池大小
              ConnectingIOReactor ioReactor;
              ioReactor = new DefaultConnectingIOReactor(ioReactorConfig);
              PoolingNHttpClientConnectionManager conMgr = new PoolingNHttpClientConnectionManager(ioReactor, null,
                      sessionStrategyRegistry, null);
      
              if (poolSize > 0) {
                  conMgr.setMaxTotal(poolSize);
              }
      
              if (maxPerRoute > 0) {
                  conMgr.setDefaultMaxPerRoute(maxPerRoute);
              } else {
                  conMgr.setDefaultMaxPerRoute(10);
              }
      
              ConnectionConfig connectionConfig = ConnectionConfig.custom().setMalformedInputAction(CodingErrorAction.IGNORE)
                      .setUnmappableInputAction(CodingErrorAction.IGNORE)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值