org.apache.http.impl.conn.PoolingHttpClientConnectionManager Java Examples

The following examples show how to use org.apache.http.impl.conn.PoolingHttpClientConnectionManager. 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: HttpTransportClient.java    From vk-java-sdk with MIT License 8 votes vote down vote up
public HttpTransportClient(int retryAttemptsNetworkErrorCount, int retryAttemptsInvalidStatusCount) {
    this.retryAttemptsNetworkErrorCount = retryAttemptsNetworkErrorCount;
    this.retryAttemptsInvalidStatusCount = retryAttemptsInvalidStatusCount;

    CookieStore cookieStore = new BasicCookieStore();
    RequestConfig requestConfig = RequestConfig.custom()
            .setSocketTimeout(SOCKET_TIMEOUT_MS)
            .setConnectTimeout(CONNECTION_TIMEOUT_MS)
            .setConnectionRequestTimeout(CONNECTION_TIMEOUT_MS)
            .setCookieSpec(CookieSpecs.STANDARD)
            .build();

    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();

    connectionManager.setMaxTotal(MAX_SIMULTANEOUS_CONNECTIONS);
    connectionManager.setDefaultMaxPerRoute(MAX_SIMULTANEOUS_CONNECTIONS);

    httpClient = HttpClients.custom()
            .setConnectionManager(connectionManager)
            .setDefaultRequestConfig(requestConfig)
            .setDefaultCookieStore(cookieStore)
            .setUserAgent(USER_AGENT)
            .build();
}
 
Example #2
Source File: SmartRestTemplateConfig.java    From smart-admin with MIT License 7 votes vote down vote up
@Bean
public HttpClient httpClient() {
    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", SSLConnectionSocketFactory.getSocketFactory())
            .build();
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
    connectionManager.setMaxTotal(maxTotal);
    connectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);

    RequestConfig requestConfig = RequestConfig.custom()
            .setSocketTimeout(socketTimeout)
            .setConnectTimeout(connectTimeout)
            .setConnectionRequestTimeout(connectionRequestTimeout)
            .build();
    return HttpClientBuilder.create()
            .setDefaultRequestConfig(requestConfig)
            .setConnectionManager(connectionManager)
            .build();
}
 
Example #3
Source File: HttpRequestHandler.java    From Asqatasun with GNU Affero General Public License v3.0 6 votes vote down vote up
private CloseableHttpClient getHttpClient(String url) {
     RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(socketTimeout)
.setConnectTimeout(connectionTimeout)
.build();
     HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
     httpClientBuilder.setDefaultRequestConfig(requestConfig);
     httpClientBuilder.setConnectionManager(new PoolingHttpClientConnectionManager());
     httpClientBuilder.setUserAgent(ASQATASUN_USER_AGENT);
     if (isProxySet(url)) {
         LOGGER.debug(("Set proxy with " + proxyHost + " and " + proxyPort));
         httpClientBuilder.setProxy(new HttpHost(proxyHost, Integer.valueOf(proxyPort)));
         if (isProxyCredentialSet()) {
             CredentialsProvider credsProvider = new BasicCredentialsProvider();
             credsProvider.setCredentials(
                     new AuthScope(proxyHost, Integer.valueOf(proxyPort)),
                     new UsernamePasswordCredentials(proxyUser, proxyPassword));
             httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
             LOGGER.debug(("Set proxy credentials " + proxyHost + " and " + proxyPort + " and " + proxyUser + " and " + proxyPassword));
         }
     }
     return httpClientBuilder.build();
 }
 
Example #4
Source File: DockerClient.java    From rapid with MIT License 6 votes vote down vote up
private void init() {
    final URI originalUri = URI.create(DEFAULT_UNIX_ENDPOINT);
    sanitizeUri = UnixFactory.sanitizeUri(originalUri);

    final RegistryBuilder<ConnectionSocketFactory> registryBuilder =
            RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("https", SSLConnectionSocketFactory.getSocketFactory())
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .register("unix", new UnixFactory(originalUri));

    final PoolingHttpClientConnectionManager cm =
            new PoolingHttpClientConnectionManager(registryBuilder.build());

    final RequestConfig requestConfig = RequestConfig.custom()
            .setConnectionRequestTimeout((int) SECONDS.toMillis(5))
            .setConnectTimeout((int) SECONDS.toMillis(5))
            .setSocketTimeout((int) SECONDS.toMillis(30))
            .build();

    final ClientConfig config = new ClientConfig()
            .connectorProvider(new ApacheConnectorProvider())
            .property(ApacheClientProperties.CONNECTION_MANAGER, cm)
            .property(ApacheClientProperties.REQUEST_CONFIG, requestConfig);

    client = ClientBuilder.newBuilder().withConfig(config).build();
}
 
Example #5
Source File: AbstractNotifierConfig.java    From github-autostatus-plugin with MIT License 6 votes vote down vote up
/**
 * Gets an HTTP client that can be used to make requests.
 *
 * @return HTTP client
 */
public CloseableHttpClient getHttpClient(boolean ignoreSSL) throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    if (ignoreSSL) {
        final SSLContext sslContext = new SSLContextBuilder()
                .loadTrustMaterial(null, (x509CertChain, authType) -> true)
                .build();
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
                RegistryBuilder.<ConnectionSocketFactory>create()
                        .register("http", PlainConnectionSocketFactory.INSTANCE)
                        .register("https", new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE))
                        .build()
        );
        return HttpClientBuilder.create()
                .setSSLContext(sslContext)
                .setConnectionManager(connectionManager)
                .build();
    }
    return HttpClients.createDefault();
}
 
Example #6
Source File: TestHttpClient4.java    From davmail with GNU General Public License v2.0 6 votes vote down vote up
public void testSSL() throws IOException {

        RegistryBuilder<ConnectionSocketFactory> schemeRegistry = RegistryBuilder.create();

        schemeRegistry.register("https", new SSLConnectionSocketFactory(new DavGatewaySSLSocketFactory(),
                SSLConnectionSocketFactory.getDefaultHostnameVerifier()));

        PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(schemeRegistry.build());
        HttpClientBuilder clientBuilder = HttpClientBuilder.create()
                .disableRedirectHandling()
                .setConnectionManager(poolingHttpClientConnectionManager);
        try (CloseableHttpClient httpClient = clientBuilder.build()) {

            HttpGet httpget = new HttpGet("https://outlook.office365.com");
            try (CloseableHttpResponse response = httpClient.execute(httpget)) {
                assertEquals(HttpStatus.SC_MOVED_TEMPORARILY, response.getStatusLine().getStatusCode());
            }
        }
    }
 
Example #7
Source File: HttpClientConfig.java    From SpringBootBucket with MIT License 6 votes vote down vote up
@Bean
public Runnable idleConnectionMonitor(final PoolingHttpClientConnectionManager connectionManager) {
    return new Runnable() {
        @Override
        @Scheduled(fixedDelay = 10000)
        public void run() {
            try {
                if (connectionManager != null) {
                    LOGGER.trace("run IdleConnectionMonitor - Closing expired and idle connections...");
                    connectionManager.closeExpiredConnections();
                    connectionManager.closeIdleConnections(p.getCloseIdleConnectionWaitTimeSecs(), TimeUnit.SECONDS);
                } else {
                    LOGGER.trace("run IdleConnectionMonitor - Http Client Connection manager is not initialised");
                }
            } catch (Exception e) {
                LOGGER.error("run IdleConnectionMonitor - Exception occurred. msg={}, e={}", e.getMessage(), e);
            }
        }
    };
}
 
Example #8
Source File: HttpClient4Utils.java    From ZTuoExchange_framework with MIT License 6 votes vote down vote up
/**
 * 实例化HttpClient
 *
 * @param maxTotal
 * @param maxPerRoute
 * @param socketTimeout
 * @param connectTimeout
 * @param connectionRequestTimeout
 * @return
 */
public static HttpClient createHttpClient(int maxTotal, int maxPerRoute, int socketTimeout, int connectTimeout,
                                          int connectionRequestTimeout) {
    RequestConfig defaultRequestConfig = RequestConfig.custom()
            .setSocketTimeout(socketTimeout)
            .setConnectTimeout(connectTimeout)
            .setConnectionRequestTimeout(connectionRequestTimeout).build();

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(maxTotal);
    cm.setDefaultMaxPerRoute(maxPerRoute);
    cm.setValidateAfterInactivity(200); // 一个连接idle超过200ms,再次被使用之前,需要先做validation
    CloseableHttpClient httpClient = HttpClients.custom()
            .setConnectionManager(cm)
            .setConnectionTimeToLive(30, TimeUnit.SECONDS)
            .setRetryHandler(new StandardHttpRequestRetryHandler(3, true)) // 配置出错重试
            .setDefaultRequestConfig(defaultRequestConfig).build();

    startMonitorThread(cm);

    return httpClient;
}
 
Example #9
Source File: HttpClientServiceImpl.java    From smockin with Apache License 2.0 6 votes vote down vote up
private CloseableHttpClient noSslHttpClient() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {

        final SSLContext sslContext = new SSLContextBuilder()
                .loadTrustMaterial(null, (x509CertChain, authType) -> true)
                .build();

        return HttpClientBuilder.create()
                .setSSLContext(sslContext)
                .setConnectionManager(
                        new PoolingHttpClientConnectionManager(
                                RegistryBuilder.<ConnectionSocketFactory>create()
                                        .register("http", PlainConnectionSocketFactory.INSTANCE)
                                        .register("https", new SSLConnectionSocketFactory(sslContext,
                                                NoopHostnameVerifier.INSTANCE))
                                        .build()
                        ))
                .build();
    }
 
Example #10
Source File: HttpClientFactory.java    From riptide with MIT License 6 votes vote down vote up
public static HttpClientConnectionManager createHttpClientConnectionManager(final Client client)
        throws GeneralSecurityException, IOException {

    final Connections connections = client.getConnections();

    final PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager(
            RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .register("https", new SSLConnectionSocketFactory(createSSLContext(client)))
                    .build(),
            null, // connection factory
            null, // scheme port resolver
            null, // dns resolver
            connections.getTimeToLive().getAmount(),
            connections.getTimeToLive().getUnit());

    manager.setMaxTotal(connections.getMaxTotal());
    manager.setDefaultMaxPerRoute(connections.getMaxPerRoute());

    return manager;
}
 
Example #11
Source File: HomeGraphAPI.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Inject
public HomeGraphAPI(GoogleConfig config,
      GoogleRpcContext rpcContext,
      ProductCatalogManager prodCat,
      GoogleWhitelist whitelist,
      @Named(EXECUTOR_NAME) HashedWheelTimer executor
) {
   this.config = config;
   requestConfig = RequestConfig.custom()
      .setConnectionRequestTimeout(config.getConnectionRequestTimeoutMs())
      .setConnectTimeout(config.getConnectionTimeoutMs())
      .setSocketTimeout(config.getSocketTimeoutMs())
      .build();

   pool = new PoolingHttpClientConnectionManager(config.getTimeToLiveMs(), TimeUnit.MILLISECONDS);
   pool.setDefaultMaxPerRoute(config.getRouteMaxConnections());
   pool.setMaxTotal(config.getMaxConnections());
   pool.setValidateAfterInactivity(config.getValidateAfterInactivityMs());
   this.gRpcContext = rpcContext;
   this.prodCat = prodCat;
   this.whitelist = whitelist;
   this.executor = executor;
}
 
Example #12
Source File: HttpClientConnectionManagementLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
// @Ignore
// 4.2 Tester Version
/*tester*/ public final void whenExecutingSameRequestsInDifferentThreads_thenUseDefaultConnLimit() throws InterruptedException, IOException {
    poolingConnManager = new PoolingHttpClientConnectionManager();
    client = HttpClients.custom().setConnectionManager(poolingConnManager).build();
    final TesterVersion_MultiHttpClientConnThread thread1 = new TesterVersion_MultiHttpClientConnThread(client, new HttpGet("http://www.google.com"), poolingConnManager);
    final TesterVersion_MultiHttpClientConnThread thread2 = new TesterVersion_MultiHttpClientConnThread(client, new HttpGet("http://www.google.com"), poolingConnManager);
    final TesterVersion_MultiHttpClientConnThread thread3 = new TesterVersion_MultiHttpClientConnThread(client, new HttpGet("http://www.google.com"), poolingConnManager);
    thread1.start();
    thread2.start();
    thread3.start();
    thread1.join(10000);
    thread2.join(10000);
    thread3.join(10000);
}
 
Example #13
Source File: ClientConnection.java    From yacy_grid_mcp with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static PoolingHttpClientConnectionManager getConnctionManager(){

        Registry<ConnectionSocketFactory> socketFactoryRegistry = null;
        try {
            SSLConnectionSocketFactory trustSelfSignedSocketFactory = new SSLConnectionSocketFactory(
                        new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(),
                        new TrustAllHostNameVerifier());
            socketFactoryRegistry = RegistryBuilder
                    .<ConnectionSocketFactory> create()
                    .register("http", new PlainConnectionSocketFactory())
                    .register("https", trustSelfSignedSocketFactory)
                    .build();
        } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
            Data.logger.warn("", e);
        }
        
        PoolingHttpClientConnectionManager cm = (socketFactoryRegistry != null) ? 
                new PoolingHttpClientConnectionManager(socketFactoryRegistry):
                new PoolingHttpClientConnectionManager();
        
        // twitter specific options
        cm.setMaxTotal(2000);
        cm.setDefaultMaxPerRoute(200);
        
        return cm;
    }
 
Example #14
Source File: RESTInvoker.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
private void configureHttpClient() {
    int connectionTimeout = 120000;
    int socketTimeout = 120000;
    int maxTotalConnectionsPerRoute = 100;
    int maxTotalConnections = 100;
    RequestConfig defaultRequestConfig = RequestConfig.custom()
            .setExpectContinueEnabled(true)
            .setConnectTimeout(connectionTimeout)
            .setSocketTimeout(socketTimeout)
            .build();
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setDefaultMaxPerRoute(maxTotalConnectionsPerRoute);
    connectionManager.setMaxTotal(maxTotalConnections);
    client = HttpClients.custom()
            .setConnectionManager(connectionManager)
            .setDefaultRequestConfig(defaultRequestConfig)
            .build();
    if (log.isDebugEnabled()) {
        log.debug("REST client initialized with " +
                "maxTotalConnection = " + maxTotalConnections +
                "maxConnectionsPerRoute = " + maxTotalConnectionsPerRoute +
                "connectionTimeout = " + connectionTimeout);
    }

}
 
Example #15
Source File: HttpClientUtil.java    From ATest with GNU General Public License v3.0 6 votes vote down vote up
public static CloseableHttpClient getHttpClient(final int executionCount, int retryInterval) {
	ServiceUnavailableRetryStrategy serviceUnavailableRetryStrategy = new MyServiceUnavailableRetryStrategy.Builder()
			.executionCount(executionCount).retryInterval(retryInterval).build();
	return HttpClientBuilder.create().setRetryHandler(new HttpRequestRetryHandler() {
		@Override
		public boolean retryRequest(IOException e, int count, HttpContext contr) {
			if (count >= executionCount) {
				// Do not retry if over max retry count
				return false;
			}
			if (e instanceof InterruptedIOException) {
				// Timeout
				return true;
			}

			return true;
		}
	}).setServiceUnavailableRetryStrategy(serviceUnavailableRetryStrategy)
			.setConnectionManager(new PoolingHttpClientConnectionManager()).build();
}
 
Example #16
Source File: HttpClientUtil.java    From ATest with GNU General Public License v3.0 6 votes vote down vote up
public static CloseableHttpClient getHttpClient(final int executionCount, int retryInterval) {
	ServiceUnavailableRetryStrategy serviceUnavailableRetryStrategy = new MyServiceUnavailableRetryStrategy.Builder()
			.executionCount(executionCount).retryInterval(retryInterval).build();
	return HttpClientBuilder.create().setRetryHandler(new HttpRequestRetryHandler() {
		@Override
		public boolean retryRequest(IOException e, int count, HttpContext contr) {
			if (count >= executionCount) {
				// Do not retry if over max retry count
				return false;
			}
			if (e instanceof InterruptedIOException) {
				// Timeout
				return true;
			}

			return true;
		}
	}).setServiceUnavailableRetryStrategy(serviceUnavailableRetryStrategy)
			.setConnectionManager(new PoolingHttpClientConnectionManager()).build();
}
 
Example #17
Source File: HttpProtocolParent.java    From dtsopensource with Apache License 2.0 6 votes vote down vote up
private CloseableHttpClient createHttpClient(String hostname, int port) {
    ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
    LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory.getSocketFactory();
    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create()
            .register("http", plainsf).register("https", sslsf).build();
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
    // 将最大连接数增加
    cm.setMaxTotal(maxTotal);
    // 将每个路由基础的连接增加
    cm.setDefaultMaxPerRoute(maxPerRoute);
    HttpHost httpHost = new HttpHost(hostname, port);
    // 将目标主机的最大连接数增加
    cm.setMaxPerRoute(new HttpRoute(httpHost), maxRoute);
    // 请求重试处理
    return HttpClients.custom().setConnectionManager(cm).setRetryHandler(httpRequestRetryHandler).build();
}
 
Example #18
Source File: BmsHttpTransport.java    From spring-cloud-formula with Apache License 2.0 6 votes vote down vote up
public BmsHttpTransport(HttpRequestInterceptor requestInterceptor) {
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setMaxTotal(DEFAULT_MAX_CONNECTIONS);
    connectionManager.setDefaultMaxPerRoute(DEFAULT_MAX_PER_ROUTE_CONNECTIONS);

    RequestConfig requestConfig = RequestConfig.custom().
            setConnectTimeout(DEFAULT_CONNECTION_TIMEOUT).
            setConnectionRequestTimeout(DEFAULT_CONNECTION_TIMEOUT).
            setSocketTimeout(DEFAULT_READ_TIMEOUT).
            build();

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().
            setConnectionManager(connectionManager).
            setDefaultRequestConfig(requestConfig).
            useSystemProperties();

    if (requestInterceptor != null) {
        httpClientBuilder.addInterceptorFirst(requestInterceptor);
    }

    this.httpClient = httpClientBuilder.build();
}
 
Example #19
Source File: HttpUtils.java    From ScriptSpider with Apache License 2.0 6 votes vote down vote up
/**
 * 创建httpclient连接池,并初始化httpclient
 */
public void init() {
    try {
        SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null,
                new TrustSelfSignedStrategy())
                .build();
        HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext, hostnameVerifier);
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslsf)
                .build();
        httpClientConnectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        // Increase max total connection to 200
        httpClientConnectionManager.setMaxTotal(maxTotalPool);
        // Increase default max connection per route to 20
        httpClientConnectionManager.setDefaultMaxPerRoute(maxConPerRoute);
        SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(socketTimeout).build();
        httpClientConnectionManager.setDefaultSocketConfig(socketConfig);
    } catch (Exception e) {

    }
}
 
Example #20
Source File: AbstractBimServerClientFactory.java    From BIMserver with GNU Affero General Public License v3.0 5 votes vote down vote up
public void initHttpClient() {
		HttpClientBuilder builder = HttpClientBuilder.create();
		
		PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
		connManager.setMaxTotal(100);
		connManager.setDefaultMaxPerRoute(100);
		builder.setConnectionManager(connManager);
		builder.disableAutomaticRetries();
		
//		builder.addInterceptorFirst(new HttpRequestInterceptor() {
//			public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
//				if (!request.containsHeader("Accept-Encoding")) {
//					request.addHeader("Accept-Encoding", "gzip");
//				}
//			}
//		});
//
//		builder.addInterceptorFirst(new HttpResponseInterceptor() {
//			public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException {
//				HttpEntity entity = response.getEntity();
//				if (entity != null) {
//					Header ceheader = entity.getContentEncoding();
//					if (ceheader != null) {
//						HeaderElement[] codecs = ceheader.getElements();
//						for (int i = 0; i < codecs.length; i++) {
//							if (codecs[i].getName().equalsIgnoreCase("gzip")) {
//								response.setEntity(new GzipDecompressingEntity(response.getEntity()));
//								return;
//							}
//						}
//					}
//				}
//			}
//		});

		httpClient = builder.build();
	}
 
Example #21
Source File: ManagedHttpClientTest.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
@Test
public void objectTest() {
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder.setConnectionManager(connectionManager);
    CloseableHttpClient client = clientBuilder.build();
    ManagedHttpClient managedHttpClient = new ManagedHttpClient(client, connectionManager);
    Assert.assertSame(client, managedHttpClient.getHttpClient());
    Assert.assertSame(connectionManager, managedHttpClient.getConnectionManager());
}
 
Example #22
Source File: HTTPStrictTransportSecurityIT.java    From qonduit with Apache License 2.0 5 votes vote down vote up
@Test
public void testHttpRequestGet() throws Exception {

    RequestConfig.Builder req = RequestConfig.custom();
    req.setConnectTimeout(5000);
    req.setConnectionRequestTimeout(5000);
    req.setRedirectsEnabled(false);
    req.setSocketTimeout(5000);
    req.setExpectContinueEnabled(false);

    HttpGet get = new HttpGet("http://127.0.0.1:54322/login");
    get.setConfig(req.build());

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setDefaultMaxPerRoute(5);

    HttpClientBuilder builder = HttpClients.custom();
    builder.disableAutomaticRetries();
    builder.disableRedirectHandling();
    builder.setConnectionTimeToLive(5, TimeUnit.SECONDS);
    builder.setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE);
    builder.setConnectionManager(cm);
    CloseableHttpClient client = builder.build();

    String s = client.execute(get, new ResponseHandler<String>() {

        @Override
        public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            assertEquals(301, response.getStatusLine().getStatusCode());
            return "success";
        }

    });
    assertEquals("success", s);

}
 
Example #23
Source File: BaseClient.java    From galaxy-sdk-java with Apache License 2.0 5 votes vote down vote up
private HttpClient createHttpClient(ConnectionConfig config) {
  RequestConfig requestConfig = RequestConfig.custom()
      .setConnectTimeout(config.getConnectionTimeoutMs())
      .setSocketTimeout(config.getSocketTimeoutMs())
      .build();

  RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create();
  registryBuilder.register("http", new PlainConnectionSocketFactory());

  if (config.isHttpsEnabled()) {
    SSLContext sslContext = SSLContexts.createSystemDefault();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
        sslContext,
        SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    registryBuilder.register("https", sslsf);
  }
  connectionManager = new PoolingHttpClientConnectionManager(registryBuilder.build());
  connectionManager.setDefaultMaxPerRoute(config.getMaxConnection());
  connectionManager.setMaxTotal(config.getMaxConnection());

  HttpClient httpClient = HttpClients.custom()
      .setConnectionManager(connectionManager)
      .setDefaultRequestConfig(requestConfig)
      .setRetryHandler(new DefaultHttpRequestRetryHandler(3, false))
      .build();
  return httpClient;
}
 
Example #24
Source File: HTTPConnectionManager.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
public HttpClientConnectionManager getHttpConnectionManager() {
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    // TODO: Introduce configurable variable for Max total and max per router variables.
    cm.setMaxTotal(MAX_TOTAL_CONNECTIONS);
    cm.setDefaultMaxPerRoute(DEFAULT_MAX_PER_ROUTE);
    //HttpHost localhost = new HttpHost("localhost", 80);
    //cm.setMaxPerRoute(new HttpRoute(localhost), 50);
    return cm;
}
 
Example #25
Source File: HTTPInvoker.java    From product-emm with Apache License 2.0 5 votes vote down vote up
private static HttpClient createHttpClient()
        throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    HttpClientBuilder b = HttpClientBuilder.create();

    // setup a Trust Strategy that allows all certificates.
    //
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
        public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            return true;
        }
    }).build();
    b.setSSLContext(sslContext);
    //b.setSSLHostnameVerifier(new NoopHostnameVerifier());

    // don't check Hostnames, either.
    //      -- use SSLConnectionSocketFactory.getDefaultHostnameVerifier(), if you don't want to weaken
    HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

    // here's the special part:
    //      -- need to create an SSL Socket Factory, to use our weakened "trust strategy";
    //      -- and create a Registry, to register it.
    //
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslSocketFactory)
            .build();

    // now, we create connection-manager using our Registry.
    //      -- allows multi-threaded use
    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    b.setConnectionManager(connMgr);

    // finally, build the HttpClient;
    //      -- done!
    CloseableHttpClient client = b.build();
    return client;
}
 
Example #26
Source File: ApacheHttpConnManager.java    From xian with Apache License 2.0 5 votes vote down vote up
public static PoolingHttpClientConnectionManager create() {
	if (Holder == null) {
		synchronized (ApacheHttpConnManager.class) {
			if (Holder == null) {
				PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
				cm.setMaxTotal(500);
				cm.setDefaultMaxPerRoute(200);
				Holder = cm;
				// 连接失效监控和回收
				IdlePoolMonitor.build(cm).monitor();
			}
		}
	}
	return Holder;
}
 
Example #27
Source File: HttpUtils.java    From gatk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static synchronized CloseableHttpClient getClient() {
    if (HttpUtils.client == null) {
        HttpUtils.client = HttpClientBuilder.create()
            .setConnectionManager(new PoolingHttpClientConnectionManager())
            .setServiceUnavailableRetryStrategy(new ServiceUnavailableRetryStrategy() {
                private int interval = 1;

                @Override
                // retry at most 4 times if a 5xx status code is received, or no status line is present
                public boolean retryRequest(final HttpResponse resp, final int executionCount, final HttpContext context) {
                    if (executionCount > 4) {
                        return false;
                    }
                    if (resp.getStatusLine() == null) {
                        return true;
                    }
                    final int statusCode = resp.getStatusLine().getStatusCode();
                    return 500 <= statusCode && statusCode < 600;
                }

                @Override
                public long getRetryInterval() {
                    final int retryInterval = interval;
                    interval *= 2;
                    return retryInterval;
                }
            })
            .build();
    }
    return HttpUtils.client;
}
 
Example #28
Source File: HttpClientInstance.java    From sofa-tracer with Apache License 2.0 5 votes vote down vote up
private CloseableHttpClient getHttpClient() {
    if (this.httpClient != null) {
        return this.httpClient;
    }
    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
    connManager.setDefaultMaxPerRoute(6);
    connManager.setMaxTotal(20);
    connManager.closeIdleConnections(120, TimeUnit.SECONDS);
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    //SOFATracer
    SofaTracerHttpClientBuilder.clientBuilder(httpClientBuilder);
    httpClient = httpClientBuilder.setConnectionManager(connManager).disableAutomaticRetries()
        .setUserAgent("CLIENT_VERSION").build();
    return httpClient;
}
 
Example #29
Source File: InsightDataManager.java    From dx-java with MIT License 5 votes vote down vote up
/**
 * Create a HttpClient
 * 
 * @return a HttpClient
 */
private HttpClient createHttpClient() {
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setMaxTotal(DEFAULT_MAX_CONNECTIONS);
    connectionManager.setDefaultMaxPerRoute(MercadoPago.SDK.getMaxConnections());
    connectionManager.setValidateAfterInactivity(VALIDATE_INACTIVITY_INTERVAL_MS);
    DefaultHttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler(MercadoPago.SDK.getRetries(),
            false);

    HttpClientBuilder httpClientBuilder = HttpClients.custom().setConnectionManager(connectionManager)
            .setKeepAliveStrategy(new KeepAliveStrategy()).setRetryHandler(retryHandler).disableCookieManagement()
            .disableRedirectHandling();

    return httpClientBuilder.build();
}
 
Example #30
Source File: HttpClientTools.java    From LuckyFrameClient with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * httpclient��ʽ HTTP/HTTPS��ʼ��
 *
 * @param urlParam �������
 * @param cerpath  ����·��
 * @return ����HTTPCLIENT����
 */
private CloseableHttpClient iniHttpClient(String urlParam, String cerpath) throws NoSuchAlgorithmException, KeyManagementException {
    CloseableHttpClient httpclient;
    urlParam = urlParam.trim();
    if (urlParam.startsWith("http://")) {
        httpclient = HttpClients.createDefault();
    } else if (urlParam.startsWith("https://")) {
        //�����ƹ���֤�ķ�ʽ����https����
        SSLContext sslContext;
        if (null == cerpath || "".equals(cerpath.trim())) {
            LogUtil.APP.info("��ʼ����HTTPS������֤����...");
            TrustManager[] trustManagers = {new MyX509TrustManager()};
            sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustManagers, new SecureRandom());
        } else {
            LogUtil.APP.info("��ʼ����HTTPS˫����֤����...");
            String[] strcerpath = cerpath.split(";", -1);
            HttpClientTools hct = new HttpClientTools();
            sslContext = hct.sslContextKeyStore(strcerpath[0], strcerpath[1]);
        }

        // ����Э��http��https��Ӧ�Ĵ���socket���ӹ����Ķ���
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.INSTANCE)
                // ������SSL���ӻ���֤����֤����Ϣ
                // .register("https", new SSLConnectionSocketFactory(sslContext)).build();
                // ����������֤
                .register("https", new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE))
                .build();
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        connManager.setDefaultMaxPerRoute(1);
        //�����Զ����httpclient����
        httpclient = HttpClients.custom().setConnectionManager(connManager).build();
    } else {
        httpclient = HttpClients.createDefault();
    }
    return httpclient;
}