org.apache.http.conn.ManagedHttpClientConnection Java Examples

The following examples show how to use org.apache.http.conn.ManagedHttpClientConnection. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SavingConnectionDetailsHttpResponseInterceptorTests.java    From vividus with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #2
Source File: SavingConnectionDetailsHttpResponseInterceptor.java    From vividus with Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example #3
Source File: ExtendedConnectionOperator.java    From lavaplayer with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #4
Source File: SimpleHttpClientConnectionManager.java    From lavaplayer with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #5
Source File: ExtendedHttpClientBuilder.java    From lavaplayer with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #6
Source File: TracingManagedHttpClientConnectionFactory.java    From caravan with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #7
Source File: SiteToSiteRestApiClient.java    From nifi with Apache License 2.0 5 votes vote down vote up
@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);
        }
    }
}
 
Example #8
Source File: SSLCertificateLoader.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
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);
            }
		}
	};
}
 
Example #9
Source File: SimpleHttpClientConnectionManager.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
public SimpleHttpClientConnectionManager(
    HttpClientConnectionOperator connectionOperator,
    HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> factory
) {
  this.connectionOperator = connectionOperator;
  this.connectionFactory = factory != null ? factory : ManagedHttpClientConnectionFactory.INSTANCE;
}
 
Example #10
Source File: HttpClientTest.java    From netcrusher-java with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #11
Source File: SdkHttpRequestExecutor.java    From ibm-cos-sdk-java with Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example #12
Source File: AutoCleanedPoolingHttpClientConnectionManager.java    From caravan with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example #13
Source File: SiteToSiteRestApiClient.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@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);
        }
    }
}
 
Example #14
Source File: SavingConnectionDetailsHttpResponseInterceptorTests.java    From vividus with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #15
Source File: SavingConnectionDetailsHttpResponseInterceptorTests.java    From vividus with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #16
Source File: SavingConnectionDetailsHttpResponseInterceptorTests.java    From vividus with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #17
Source File: AutoCleanedPoolingHttpClientConnectionManager.java    From caravan with Apache License 2.0 4 votes vote down vote up
public AutoCleanedPoolingHttpClientConnectionManager(HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory) {
    this(0, 0, 0, 0, connFactory);
}
 
Example #18
Source File: ExtendedHttpClientBuilder.java    From lavaplayer with Apache License 2.0 4 votes vote down vote up
HttpClientConnectionManager create(
    HttpClientConnectionOperator operator,
    HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connectionFactory
);
 
Example #19
Source File: HttpSyncClient.java    From Almost-Famous with MIT License 4 votes vote down vote up
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;
}
 
Example #20
Source File: SimpleHttpClientConnectionManager.java    From lavaplayer with Apache License 2.0 4 votes vote down vote up
@Override
public void upgrade(HttpClientConnection connection, HttpRoute route, HttpContext context) throws IOException {
  ManagedHttpClientConnection managed = (ManagedHttpClientConnection) connection;
  this.connectionOperator.upgrade(managed, route.getTargetHost(), context);
}
 
Example #21
Source File: RestTemplateConfig.java    From spring-boot-cookbook with Apache License 2.0 4 votes vote down vote up
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;
    }
 
Example #22
Source File: RestTemplateConfig.java    From spring-boot-cookbook with Apache License 2.0 4 votes vote down vote up
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;
    }
 
Example #23
Source File: CertificateRetriever.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * 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();
  }
}