类org.apache.http.conn.ManagedHttpClientConnection源码实例Demo

下面列出了怎么用org.apache.http.conn.ManagedHttpClientConnection的API类实例代码及写法,或者点击链接到github查看源代码。

@Override
public void process(HttpResponse response, HttpContext context)
{
    ManagedHttpClientConnection routedConnection = (ManagedHttpClientConnection) context
            .getAttribute(HttpCoreContext.HTTP_CONNECTION);
    // Connection may be stale, when no response body is returned
    if (routedConnection.isOpen() && (response.getEntity() != null || !routedConnection.isStale()))
    {
        SSLSession sslSession = routedConnection.getSSLSession();
        boolean secure = sslSession != null;
        ConnectionDetails connectionDetails = new ConnectionDetails();
        connectionDetails.setSecure(secure);
        if (secure)
        {
            connectionDetails.setSecurityProtocol(sslSession.getProtocol());
        }
        httpTestContext.putConnectionDetails(connectionDetails);
    }
}
 
@Test
void shouldSaveConnectionDetailsForSecuredConnectionAndDoNotCheckStalenessForResponsesWithEntity()
{
    String protocol = "TLSv1.3";
    SSLSession sslSession = mock(SSLSession.class);
    when(sslSession.getProtocol()).thenReturn(protocol);
    HttpContext context = mock(HttpContext.class);
    ManagedHttpClientConnection connection = mock(ManagedHttpClientConnection.class);
    when(context.getAttribute(HttpCoreContext.HTTP_CONNECTION)).thenReturn(connection);
    when(connection.isOpen()).thenReturn(true);
    when(connection.getSSLSession()).thenReturn(sslSession);
    HttpResponse response = mock(HttpResponse.class);
    when(response.getEntity()).thenReturn(mock(HttpEntity.class));
    interceptor.process(response, context);
    verify(httpTestContext).putConnectionDetails(argThat(connectionDetails -> connectionDetails.isSecure()
            && protocol.equals(connectionDetails.getSecurityProtocol())));
    verify(connection, never()).isStale();
}
 
@Override
public ManagedHttpClientConnection create(final HttpRoute route, final ConnectionConfig config) {
    final ConnectionConfig cconfig = config != null ? config : ConnectionConfig.DEFAULT;
    CharsetDecoder chardecoder = null;
    CharsetEncoder charencoder = null;
    final Charset charset = cconfig.getCharset();
    final CodingErrorAction malformedInputAction = cconfig.getMalformedInputAction() != null ? cconfig.getMalformedInputAction() : CodingErrorAction.REPORT;
    final CodingErrorAction unmappableInputAction = cconfig.getUnmappableInputAction() != null ? cconfig.getUnmappableInputAction()
            : CodingErrorAction.REPORT;
    if (charset != null) {
        chardecoder = charset.newDecoder();
        chardecoder.onMalformedInput(malformedInputAction);
        chardecoder.onUnmappableCharacter(unmappableInputAction);
        charencoder = charset.newEncoder();
        charencoder.onMalformedInput(malformedInputAction);
        charencoder.onUnmappableCharacter(unmappableInputAction);
    }
    final String id = "http-outgoing-" + Long.toString(COUNTER.getAndIncrement());
    return new TracingManagedHttpClientConnection(id, cconfig.getBufferSize(), cconfig.getFragmentSizeHint(), chardecoder, charencoder,
            cconfig.getMessageConstraints(), incomingContentStrategy, outgoingContentStrategy, requestWriterFactory, responseParserFactory, logFunc);
}
 
源代码4 项目: lavaplayer   文件: ExtendedHttpClientBuilder.java
private static HttpClientConnectionManager createDefaultConnectionManager(
    HttpClientConnectionOperator operator,
    HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connectionFactory
) {
  PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager(
      operator,
      connectionFactory,
      -1,
      TimeUnit.MILLISECONDS
  );

  manager.setMaxTotal(3000);
  manager.setDefaultMaxPerRoute(1500);

  return manager;
}
 
@Override
public void connect(
    HttpClientConnection connection,
    HttpRoute route,
    int connectTimeout,
    HttpContext context
) throws IOException {
  HttpHost host;

  if (route.getProxyHost() != null) {
    host = route.getProxyHost();
  } else {
    host = route.getTargetHost();
  }

  InetSocketAddress localAddress = route.getLocalSocketAddress();

  ManagedHttpClientConnection managed = (ManagedHttpClientConnection) connection;
  this.connectionOperator.connect(managed, host, localAddress, connectTimeout, this.socketConfig, context);
}
 
源代码6 项目: lavaplayer   文件: ExtendedConnectionOperator.java
@Override
public void upgrade(ManagedHttpClientConnection connection, HttpHost host, HttpContext context) throws IOException {
  ConnectionSocketFactory socketFactory = getSocketFactory(host, HttpClientContext.adapt(context));

  if (!(socketFactory instanceof LayeredConnectionSocketFactory)) {
    throw new UnsupportedSchemeException(host.getSchemeName() +
        " protocol does not support connection upgrade");
  }

  LayeredConnectionSocketFactory layeredFactory = (LayeredConnectionSocketFactory) socketFactory;

  Socket socket = connection.getSocket();
  int port = this.schemePortResolver.resolve(host);
  socket = layeredFactory.createLayeredSocket(socket, host.getHostName(), port, context);

  connection.bind(socket);
}
 
@Test
void shouldSaveNoConnectionDetailsIfConnectionClosed()
{
    HttpContext context = mock(HttpContext.class);
    ManagedHttpClientConnection connection = mock(ManagedHttpClientConnection.class);
    when(connection.isOpen()).thenReturn(Boolean.FALSE);
    when(context.getAttribute(HttpCoreContext.HTTP_CONNECTION)).thenReturn(connection);
    intercept(context);
    verifyNoInteractions(httpTestContext);
    verify(connection, never()).isStale();
}
 
private static HttpContext mockHttpContextWithNonStaledConnection(SSLSession sslSession)
{
    HttpContext context = mock(HttpContext.class);
    ManagedHttpClientConnection connection = mockHttpConnection(Boolean.FALSE, context, Boolean.TRUE);
    when(connection.getSSLSession()).thenReturn(sslSession);
    return context;
}
 
private static ManagedHttpClientConnection mockHttpConnection(Boolean stale, HttpContext context, Boolean closed)
{
    ManagedHttpClientConnection connection = mock(ManagedHttpClientConnection.class);
    when(connection.isStale()).thenReturn(stale);
    when(context.getAttribute(HttpCoreContext.HTTP_CONNECTION)).thenReturn(connection);
    when(connection.isOpen()).thenReturn(closed);
    return connection;
}
 
@Override
public void process(final HttpResponse response, final HttpContext httpContext) throws HttpException, IOException {
    final HttpCoreContext coreContext = HttpCoreContext.adapt(httpContext);
    final HttpInetConnection conn = coreContext.getConnection(HttpInetConnection.class);
    if (!conn.isOpen()) {
        return;
    }

    final SSLSession sslSession;
    if (conn instanceof ManagedHttpClientConnection) {
        sslSession = ((ManagedHttpClientConnection) conn).getSSLSession();
    } else if (conn instanceof ManagedNHttpClientConnection) {
        sslSession = ((ManagedNHttpClientConnection) conn).getSSLSession();
    } else {
        throw new RuntimeException("Unexpected connection type was used, " + conn);
    }


    if (sslSession != null) {
        final Certificate[] certChain = sslSession.getPeerCertificates();
        if (certChain == null || certChain.length == 0) {
            throw new SSLPeerUnverifiedException("No certificates found");
        }

        try {
            final X509Certificate cert = CertificateUtils.convertAbstractX509Certificate(certChain[0]);
            trustedPeerDn = cert.getSubjectDN().getName().trim();
        } catch (final CertificateException e) {
            final String msg = "Could not extract subject DN from SSL session peer certificate";
            logger.warn(msg);
            eventReporter.reportEvent(Severity.WARNING, EVENT_CATEGORY, msg);
            throw new SSLPeerUnverifiedException(msg);
        }
    }
}
 
public AutoCleanedPoolingHttpClientConnectionManager(int connectionTtl, int inactivityTimeBeforeValidate, int connectionIdleTime, int cleanCheckInterval,
        HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory) {
    super(getDefaultRegistry(), connFactory, null, null, connectionTtl > 0 ? connectionTtl : DefaultConnectionConfig.DEFAULT_CONNECTION_TTL,
            TimeUnit.MILLISECONDS);

    if (inactivityTimeBeforeValidate <= 0)
        inactivityTimeBeforeValidate = DefaultConnectionConfig.DEFAULT_INACTIVITY_TIME_BEFORE_VALIDATE;
    setValidateAfterInactivity(inactivityTimeBeforeValidate);

    _idleConnectionMonitorThread = new IdleConnectionMonitorThread(this, connectionIdleTime, cleanCheckInterval);
    _idleConnectionMonitorThread.start();
}
 
源代码12 项目: ibm-cos-sdk-java   文件: SdkHttpRequestExecutor.java
@Override
protected HttpResponse doSendRequest(
        final HttpRequest request,
        final HttpClientConnection conn,
        final HttpContext context)
            throws IOException, HttpException {
    AWSRequestMetrics awsRequestMetrics = (AWSRequestMetrics) context
            .getAttribute(AWSRequestMetrics.class.getSimpleName());

    if (awsRequestMetrics == null) {
        return super.doSendRequest(request, conn, context);
    }
    if (conn instanceof ManagedHttpClientConnection) {
        ManagedHttpClientConnection managedConn = (ManagedHttpClientConnection)conn;
        Socket sock = managedConn.getSocket();
        if (sock instanceof SdkMetricsSocket) {
            SdkMetricsSocket sdkMetricsSocket = (SdkMetricsSocket)sock;
            sdkMetricsSocket.setMetrics(awsRequestMetrics);
        } else if (sock instanceof SdkSSLMetricsSocket) {
            SdkSSLMetricsSocket sdkSSLMetricsSocket = (SdkSSLMetricsSocket)sock;
            sdkSSLMetricsSocket.setMetrics(awsRequestMetrics);
        }
    }
    awsRequestMetrics.startEvent(Field.HttpClientSendRequestTime);
    try {
        return super.doSendRequest(request, conn, context);
    } finally {
        awsRequestMetrics.endEvent(Field.HttpClientSendRequestTime);
    }
}
 
源代码13 项目: netcrusher-java   文件: HttpClientTest.java
@Before
public void setUp() throws Exception {
    reactor = new NioReactor();

    crusher = TcpCrusherBuilder.builder()
            .withReactor(reactor)
            .withBindAddress("127.0.0.1", CRUSHER_PORT)
            .withConnectAddress(REMOTE_HOST, REMOTE_PORT)
            .buildAndOpen();

    DnsResolver dnsResolver = new SystemDefaultDnsResolver() {
        @Override
        public InetAddress[] resolve(final String host) throws UnknownHostException {
            if (host.equalsIgnoreCase(REMOTE_HOST)) {
                return new InetAddress[] { InetAddress.getByAddress(new byte[] {127, 0, 0, 1}) };
            } else {
                return super.resolve(host);
            }
        }
    };

    HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> httpConnectionFactory =
            new ManagedHttpClientConnectionFactory();

    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .build();

    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
            socketFactoryRegistry, httpConnectionFactory, dnsResolver);

    http = HttpClients.createMinimal(connectionManager);
}
 
public SimpleHttpClientConnectionManager(
    HttpClientConnectionOperator connectionOperator,
    HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> factory
) {
  this.connectionOperator = connectionOperator;
  this.connectionFactory = factory != null ? factory : ManagedHttpClientConnectionFactory.INSTANCE;
}
 
源代码15 项目: dss   文件: SSLCertificateLoader.java
private HttpResponseInterceptor getHttpResponseInterceptor() {
	return new HttpResponseInterceptor() {
		@Override
		public void process(HttpResponse response, HttpContext context) throws HttpException, IOException {
			ManagedHttpClientConnection routedConnection = (ManagedHttpClientConnection)context.getAttribute(HttpCoreContext.HTTP_CONNECTION);
            SSLSession sslSession = routedConnection.getSSLSession();
            if (sslSession != null) {
                Certificate[] certificates = sslSession.getPeerCertificates();
                context.setAttribute(PEER_CERTIFICATES, certificates);
            }
		}
	};
}
 
源代码16 项目: nifi   文件: SiteToSiteRestApiClient.java
@Override
public void process(final HttpResponse response, final HttpContext httpContext) throws HttpException, IOException {
    final HttpCoreContext coreContext = HttpCoreContext.adapt(httpContext);
    final HttpInetConnection conn = coreContext.getConnection(HttpInetConnection.class);
    if (!conn.isOpen()) {
        return;
    }

    final SSLSession sslSession;
    if (conn instanceof ManagedHttpClientConnection) {
        sslSession = ((ManagedHttpClientConnection) conn).getSSLSession();
    } else if (conn instanceof ManagedNHttpClientConnection) {
        sslSession = ((ManagedNHttpClientConnection) conn).getSSLSession();
    } else {
        throw new RuntimeException("Unexpected connection type was used, " + conn);
    }


    if (sslSession != null) {
        final Certificate[] certChain = sslSession.getPeerCertificates();
        if (certChain == null || certChain.length == 0) {
            throw new SSLPeerUnverifiedException("No certificates found");
        }

        try {
            final X509Certificate cert = CertificateUtils.convertAbstractX509Certificate(certChain[0]);
            trustedPeerDn = cert.getSubjectDN().getName().trim();
        } catch (final CertificateException e) {
            final String msg = "Could not extract subject DN from SSL session peer certificate";
            logger.warn(msg);
            eventReporter.reportEvent(Severity.WARNING, EVENT_CATEGORY, msg);
            throw new SSLPeerUnverifiedException(msg);
        }
    }
}
 
源代码17 项目: Almost-Famous   文件: HttpSyncClient.java
public CloseableHttpClient createSyncClient(boolean proxy)
        throws Exception {

    HttpMessageParserFactory<HttpResponse> responseParserFactory = new DefaultHttpResponseParserFactory();
    HttpMessageWriterFactory<HttpRequest> requestWriterFactory = new DefaultHttpRequestWriterFactory();

    HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory = new ManagedHttpClientConnectionFactory(
            requestWriterFactory, responseParserFactory);

    SSLContext sslcontext = SSLContexts.createSystemDefault();

    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", new SSLConnectionSocketFactory(sslcontext))
            .build();

    // Create a connection manager with custom configuration.
    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(
            socketFactoryRegistry, connFactory);

    // Create socket configuration
    SocketConfig socketConfig = SocketConfig.custom()
            .setTcpNoDelay(true)
            .build();
    // Configure the connection manager to use socket configuration either
    // by default or for a specific host.
    connManager.setDefaultSocketConfig(socketConfig);
    connManager.setSocketConfig(new HttpHost("somehost", 80), socketConfig);
    // Validate connections after 1 sec of inactivity
    connManager.setValidateAfterInactivity(1000);

    // Create message constraints
    MessageConstraints messageConstraints = MessageConstraints.custom()
            .setMaxHeaderCount(200)
            .setMaxLineLength(2000)
            .build();
    // Create connection configuration
    ConnectionConfig connectionConfig = ConnectionConfig.custom()
            .setMalformedInputAction(CodingErrorAction.IGNORE)
            .setUnmappableInputAction(CodingErrorAction.IGNORE)
            .setCharset(Consts.UTF_8)
            .setMessageConstraints(messageConstraints)
            .build();
    // Configure the connection manager to use connection configuration either
    // by default or for a specific host.
    connManager.setDefaultConnectionConfig(connectionConfig);

    // Configure total max or per route limits for persistent connections
    // that can be kept in the pool or leased by the connection manager.
    connManager.setMaxTotal(poolSize);
    if (maxPerRoute > 0) {
        connManager.setDefaultMaxPerRoute(maxPerRoute);
    } else {
        connManager.setDefaultMaxPerRoute(10);
    }

    // Use custom cookie store if necessary.
    CookieStore cookieStore = new BasicCookieStore();
    // Use custom credentials provider if necessary.
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    // Create global request configuration
    RequestConfig defaultRequestConfig = RequestConfig.custom()
            .setConnectTimeout(connectTimeout)
            .setSocketTimeout(socketTimeout)
            .setConnectionRequestTimeout(connectionRequestTimeout)
            .setCookieSpec(CookieSpecs.DEFAULT)
            .setExpectContinueEnabled(true)
            .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
            .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC))
            .build();

    // Create an HttpClient with the given custom dependencies and configuration.
    CloseableHttpClient httpclient = HttpClients.custom()
            .setConnectionManager(connManager)
            .setDefaultCookieStore(cookieStore)
            .setDefaultCredentialsProvider(credentialsProvider)
            .setDefaultRequestConfig(defaultRequestConfig)
            .build();

    return httpclient;
}
 
public AutoCleanedPoolingHttpClientConnectionManager(HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory) {
    this(0, 0, 0, 0, connFactory);
}
 
源代码19 项目: lavaplayer   文件: ExtendedHttpClientBuilder.java
HttpClientConnectionManager create(
    HttpClientConnectionOperator operator,
    HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connectionFactory
);
 
@Override
public void upgrade(HttpClientConnection connection, HttpRoute route, HttpContext context) throws IOException {
  ManagedHttpClientConnection managed = (ManagedHttpClientConnection) connection;
  this.connectionOperator.upgrade(managed, route.getTargetHost(), context);
}
 
源代码21 项目: spring-boot-cookbook   文件: RestTemplateConfig.java
private CloseableHttpClient getHttpClient() {
        //注册访问协议相关的Socket工厂
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.INSTANCE)
                .register("https", SSLConnectionSocketFactory.getSocketFactory())
                .build();

        //HttpConnectionFactory:配置写请求/解析响应处理器
        HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connectionFactory = new ManagedHttpClientConnectionFactory(
                DefaultHttpRequestWriterFactory.INSTANCE,
                DefaultHttpResponseParserFactory.INSTANCE
        );

        //DNS解析器
        DnsResolver dnsResolver = SystemDefaultDnsResolver.INSTANCE;
        //创建连接池管理器
        PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager(socketFactoryRegistry, connectionFactory, dnsResolver);
        //设置默认的socket参数
        manager.setDefaultSocketConfig(SocketConfig.custom().setTcpNoDelay(true).build());
        manager.setMaxTotal(300);//设置最大连接数。高于这个值时,新连接请求,需要阻塞,排队等待
        //路由是对MaxTotal的细分。
        // 每个路由实际最大连接数默认值是由DefaultMaxPerRoute控制。
        // MaxPerRoute设置的过小,无法支持大并发:ConnectionPoolTimeoutException:Timeout waiting for connection from pool
        manager.setDefaultMaxPerRoute(200);//每个路由的最大连接
        manager.setValidateAfterInactivity(5 * 1000);//在从连接池获取连接时,连接不活跃多长时间后需要进行一次验证,默认为2s

        //配置默认的请求参数
        RequestConfig defaultRequestConfig = RequestConfig.custom()
                .setConnectTimeout(2 * 1000)//连接超时设置为2s
                .setSocketTimeout(5 * 1000)//等待数据超时设置为5s
                .setConnectionRequestTimeout(2 * 1000)//从连接池获取连接的等待超时时间设置为2s
//                .setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("192.168.0.2", 1234))) //设置代理
                .build();

        CloseableHttpClient closeableHttpClient = HttpClients.custom()
                .setConnectionManager(manager)
                .setConnectionManagerShared(false)//连接池不是共享模式,这个共享是指与其它httpClient是否共享
                .evictIdleConnections(60, TimeUnit.SECONDS)//定期回收空闲连接
                .evictExpiredConnections()//回收过期连接
                .setConnectionTimeToLive(60, TimeUnit.SECONDS)//连接存活时间,如果不设置,则根据长连接信息决定
                .setDefaultRequestConfig(defaultRequestConfig)//设置默认的请求参数
                .setConnectionReuseStrategy(DefaultConnectionReuseStrategy.INSTANCE)//连接重用策略,即是否能keepAlive
                .setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE)//长连接配置,即获取长连接生产多长时间
                .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false))//设置重试次数,默认为3次;当前是禁用掉
                .build();

        /**
         *JVM停止或重启时,关闭连接池释放掉连接
         */
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                try {
                    closeableHttpClient.close();
                    log.info("http client closed");
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        });
        return closeableHttpClient;
    }
 
源代码22 项目: spring-boot-cookbook   文件: RestTemplateConfig.java
private CloseableHttpClient getHttpClient() {
        //注册访问协议相关的Socket工厂
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.INSTANCE)
                .register("https", SSLConnectionSocketFactory.getSocketFactory())
                .build();

        //HttpConnectionFactory:配置写请求/解析响应处理器
        HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connectionFactory = new ManagedHttpClientConnectionFactory(
                DefaultHttpRequestWriterFactory.INSTANCE,
                DefaultHttpResponseParserFactory.INSTANCE
        );

        //DNS解析器
        DnsResolver dnsResolver = SystemDefaultDnsResolver.INSTANCE;
        //创建连接池管理器
        PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager(socketFactoryRegistry, connectionFactory, dnsResolver);
        //设置默认的socket参数
        manager.setDefaultSocketConfig(SocketConfig.custom().setTcpNoDelay(true).build());
        manager.setMaxTotal(300);//设置最大连接数。高于这个值时,新连接请求,需要阻塞,排队等待
        //路由是对MaxTotal的细分。
        // 每个路由实际最大连接数默认值是由DefaultMaxPerRoute控制。
        // MaxPerRoute设置的过小,无法支持大并发:ConnectionPoolTimeoutException:Timeout waiting for connection from pool
        manager.setDefaultMaxPerRoute(200);//每个路由的最大连接
        manager.setValidateAfterInactivity(5 * 1000);//在从连接池获取连接时,连接不活跃多长时间后需要进行一次验证,默认为2s

        //配置默认的请求参数
        RequestConfig defaultRequestConfig = RequestConfig.custom()
                .setConnectTimeout(2 * 1000)//连接超时设置为2s
                .setSocketTimeout(5 * 1000)//等待数据超时设置为5s
                .setConnectionRequestTimeout(2 * 1000)//从连接池获取连接的等待超时时间设置为2s
//                .setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("192.168.0.2", 1234))) //设置代理
                .build();

        CloseableHttpClient closeableHttpClient = HttpClients.custom()
                .setConnectionManager(manager)
                .setConnectionManagerShared(false)//连接池不是共享模式,这个共享是指与其它httpClient是否共享
                .evictIdleConnections(60, TimeUnit.SECONDS)//定期回收空闲连接
                .evictExpiredConnections()//回收过期连接
                .setConnectionTimeToLive(60, TimeUnit.SECONDS)//连接存活时间,如果不设置,则根据长连接信息决定
                .setDefaultRequestConfig(defaultRequestConfig)//设置默认的请求参数
                .setConnectionReuseStrategy(DefaultConnectionReuseStrategy.INSTANCE)//连接重用策略,即是否能keepAlive
                .setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE)//长连接配置,即获取长连接生产多长时间
                .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false))//设置重试次数,默认为3次;当前是禁用掉
                .build();

        /**
         *JVM停止或重启时,关闭连接池释放掉连接
         */
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                try {
                    LOGGER.info("closing http client");
                    closeableHttpClient.close();
                    LOGGER.info("http client closed");
                } catch (IOException e) {
                    LOGGER.error(e.getMessage(), e);
                }
            }
        });
        return closeableHttpClient;
    }
 
源代码23 项目: nexus-public   文件: CertificateRetriever.java
/**
 * Retrieves certificate chain of specified host:port using https protocol.
 *
 * @param host to get certificate chain from (cannot be null)
 * @param port of host to connect to
 * @return certificate chain
 * @throws Exception Re-thrown from accessing the remote host
 */
public Certificate[] retrieveCertificatesFromHttpsServer(final String host, final int port) throws Exception {
  checkNotNull(host);

  log.info("Retrieving certificate from https://{}:{}", host, port);

  // setup custom connection manager so we can configure SSL to trust-all
  SSLContext sc = SSLContext.getInstance("TLS");
  sc.init(trustStore.getKeyManagers(), new TrustManager[]{ACCEPT_ALL_TRUST_MANAGER}, null);
  SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sc, NoopHostnameVerifier.INSTANCE);
  Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
      .register(HttpSchemes.HTTP, PlainConnectionSocketFactory.getSocketFactory())
      .register(HttpSchemes.HTTPS, sslSocketFactory).build();
  final HttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(registry);

  try {
    final AtomicReference<Certificate[]> certificates = new AtomicReference<>();

    HttpClient httpClient = httpClientManager.create(new Customizer()
    {
      @Override
      public void customize(final HttpClientPlan plan) {
        // replace connection-manager with customized version needed to fetch SSL certificates
        plan.getClient().setConnectionManager(connectionManager);

        // add interceptor to grab peer-certificates
        plan.getClient().addInterceptorFirst(new HttpResponseInterceptor()
        {
          @Override
          public void process(final HttpResponse response, final HttpContext context)
              throws HttpException, IOException
          {
            ManagedHttpClientConnection connection =
                HttpCoreContext.adapt(context).getConnection(ManagedHttpClientConnection.class);

            // grab the peer-certificates from the session
            if (connection != null) {
              SSLSession session = connection.getSSLSession();
              if (session != null) {
                certificates.set(session.getPeerCertificates());
              }
            }
          }
        });
      }
    });

    httpClient.execute(new HttpGet("https://" + host + ":" + port));

    return certificates.get();
  }
  finally {
    // shutdown single-use connection manager
    connectionManager.shutdown();
  }
}
 
 类所在包
 同包方法