當前位置: 首頁>>代碼示例>>Java>>正文


Java HttpClientBuilder.setConnectionManager方法代碼示例

本文整理匯總了Java中org.apache.http.impl.client.HttpClientBuilder.setConnectionManager方法的典型用法代碼示例。如果您正苦於以下問題:Java HttpClientBuilder.setConnectionManager方法的具體用法?Java HttpClientBuilder.setConnectionManager怎麽用?Java HttpClientBuilder.setConnectionManager使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在org.apache.http.impl.client.HttpClientBuilder的用法示例。


在下文中一共展示了HttpClientBuilder.setConnectionManager方法的9個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: testHttpRequestGet

import org.apache.http.impl.client.HttpClientBuilder; //導入方法依賴的package包/類
@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);

}
 
開發者ID:NationalSecurityAgency,項目名稱:qonduit,代碼行數:37,代碼來源:HTTPStrictTransportSecurityIT.java

示例2: getPool

import org.apache.http.impl.client.HttpClientBuilder; //導入方法依賴的package包/類
public HttpClient getPool() {

		PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
		HttpClientBuilder builder = HttpClientBuilder.create();
		connectionManager.setMaxTotal(maxConnections);
		connectionManager.setDefaultMaxPerRoute(maxConnections);
		RequestConfig config = RequestConfig.custom()
				.setConnectTimeout(timeOut)
				.setConnectionRequestTimeout(timeOut).setSocketTimeout(timeOut)
				.build();
		connectionMonitor = new IdleConnectionMonitorThread(connectionManager);
		connectionMonitor.start();
		builder.setConnectionManager(connectionManager);
		builder.setKeepAliveStrategy(myStrategy);
		CloseableHttpClient defaultHttpClient = builder
				.setDefaultRequestConfig(config).build();
		logger.debug("prepared client");
		return defaultHttpClient;
	}
 
開發者ID:zafar142007,項目名稱:FolderSync,代碼行數:20,代碼來源:Auth.java

示例3: getCustomClient

import org.apache.http.impl.client.HttpClientBuilder; //導入方法依賴的package包/類
/**
 * custom http client for server with SSL errors
 *
 * @return
 */
public final CloseableHttpClient getCustomClient() {
    try {
        HttpClientBuilder builder = HttpClientBuilder.create().useSystemProperties();
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null,
                (TrustStrategy) (X509Certificate[] arg0, String arg1) -> true).build();
        builder.setSSLContext(sslContext);
        HostnameVerifier hostnameVerifier = new NoopHostnameVerifier();
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslSocketFactory)
                .build();
        PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        builder.setConnectionManager(connMgr);
        return builder.build();
    } catch (Exception ex) {
        LOG.log(Level.SEVERE, ex.getMessage(), ex);
    }
    return getSystemClient();
}
 
開發者ID:CognizantQAHub,項目名稱:Cognizant-Intelligent-Test-Scripter,代碼行數:26,代碼來源:AbstractHttpClient.java

示例4: getHttpClient

import org.apache.http.impl.client.HttpClientBuilder; //導入方法依賴的package包/類
public HttpClient getHttpClient() {
	if (httpClient == null) {
		synchronized (this) {
			if (httpClient == null) {
				if (pool == null) { //初始化pool
					try {
						afterPropertiesSet();
					} catch (Exception e) {
						logger.error(e.getMessage(), e);
					}
				}

				HttpClientBuilder httpClientBuilder = HttpClients.custom();
				httpClientBuilder.setConnectionManager(pool);
				httpClientBuilder.setDefaultRequestConfig(RequestConfig.custom().setConnectTimeout(conntimeout).setSocketTimeout(sotimeout).build());
				httpClientBuilder.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {
					public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
						HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
						while (it.hasNext()) {
							HeaderElement he = it.nextElement();
							String param = he.getName();
							String value = he.getValue();
							if (value != null && param.equalsIgnoreCase("timeout")) {
								try {
									return Long.parseLong(value) * 1000;
								} catch (NumberFormatException ignore) {
								}
							}
						}
						// 否則保持活動5秒
						return 5 * 1000;
					}
				});
				httpClient = httpClientBuilder.build();
			}
		}
	}
	return httpClient;
}
 
開發者ID:funtl,項目名稱:framework,代碼行數:40,代碼來源:HttpClientUtil.java

示例5: initRestTemplate

import org.apache.http.impl.client.HttpClientBuilder; //導入方法依賴的package包/類
/**
 * springboot初始化restTemplate
 */
@Bean
public RestTemplate initRestTemplate() {
    // 長連接保持30秒
    PoolingHttpClientConnectionManager pollingConnectionManager = new PoolingHttpClientConnectionManager(30, TimeUnit.SECONDS);
    // 總連接數
    pollingConnectionManager.setMaxTotal(1000);
    // 同路由的並發數
    pollingConnectionManager.setDefaultMaxPerRoute(1000);

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    httpClientBuilder.setConnectionManager(pollingConnectionManager);
    // 重試次數,默認是3次,沒有開啟
    httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(2, true));
    // 保持長連接配置,需要在頭添加Keep-Alive
    httpClientBuilder.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy());

    RequestConfig.Builder builder = RequestConfig.custom();
    builder.setConnectionRequestTimeout(200);
    builder.setConnectTimeout(5000);
    builder.setSocketTimeout(5000);

    RequestConfig requestConfig = builder.build();
    httpClientBuilder.setDefaultRequestConfig(requestConfig);

    List<Header> headers = new ArrayList<>();
    headers.add(new BasicHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36"));
    headers.add(new BasicHeader("Accept-Encoding", "gzip,deflate"));
    headers.add(new BasicHeader("Accept-Language", "zh-CN"));
    headers.add(new BasicHeader("Connection", "Keep-Alive"));

    httpClientBuilder.setDefaultHeaders(headers);

    HttpClient httpClient = httpClientBuilder.build();

    // httpClient連接配置,底層是配置RequestConfig
    HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
    // 連接超時
    clientHttpRequestFactory.setConnectTimeout(5000);
    // 數據讀取超時時間,即SocketTimeout
    clientHttpRequestFactory.setReadTimeout(5000);
    // 連接不夠用的等待時間,不宜過長,必須設置,比如連接不夠用時,時間過長將是災難性的
    clientHttpRequestFactory.setConnectionRequestTimeout(200);
    // 緩衝請求數據,默認值是true。通過POST或者PUT大量發送數據時,建議將此屬性更改為false,以免耗盡內存。
    clientHttpRequestFactory.setBufferRequestBody(false);

    // 添加內容轉換器
    List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
    messageConverters.add(initStringHttpMessageConverter());
    messageConverters.add(new FormHttpMessageConverter());
    messageConverters.add(new MappingJackson2XmlHttpMessageConverter());
    messageConverters.add(new MappingJackson2HttpMessageConverter());

    RestTemplate restTemplate = new RestTemplate(messageConverters);
    restTemplate.setRequestFactory(clientHttpRequestFactory);
    restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
    return restTemplate;

}
 
開發者ID:wu05281,項目名稱:admin-shiro,代碼行數:62,代碼來源:RestTemplateConfig.java

示例6: getHttpClient

import org.apache.http.impl.client.HttpClientBuilder; //導入方法依賴的package包/類
/**
 * @see http://literatejava.com/networks/ignore-ssl-certificate-errors-apache-httpclient-4-4/
 * @return
 * @throws Exception
 */
public static synchronized HttpClient getHttpClient() throws Exception
{
   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);

   // 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 = ;

   // now, we create connection-manager using our Registry.
   //      -- allows multi-threaded use
   PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory> create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslSocketFactory).build());
   b.setConnectionManager(connMgr);

   // finally, build the HttpClient;
   //      -- done!
   HttpClient client = b.build();

   return client;
}
 
開發者ID:wellsb1,項目名稱:fort_w,代碼行數:43,代碼來源:Web.java

示例7: HttpClientTemplate

import org.apache.http.impl.client.HttpClientBuilder; //導入方法依賴的package包/類
private HttpClientTemplate() {
    // 長連接保持30秒
    PoolingHttpClientConnectionManager pollingConnectionManager = new PoolingHttpClientConnectionManager(timeToLive, TimeUnit.SECONDS);
    // 總連接數
    pollingConnectionManager.setMaxTotal(maxTotal);
    // 同路由的並發數
    pollingConnectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    httpClientBuilder.setConnectionManager(pollingConnectionManager);
    // 重試次數,默認是3次,沒有開啟
    httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(retryCount, requestSentRetryEnabled));
    // 保持長連接配置,需要在頭添加Keep-Alive
    httpClientBuilder.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy());

    List<Header> headers = new ArrayList<>();
    // 參考:http://www.cnblogs.com/sink_cup/archive/2011/03/15/http_user_agent.html
    // headers.add(new BasicHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36"));
    // 不需要設置,可能會亂碼,請參考:http://www.crifan.com/set_accept_encoding_header_to_gzip_deflate_return_messy_code/
    // headers.add(new BasicHeader("Accept-Encoding", "gzip,deflate"));
    // headers.add(new BasicHeader("Accept-Language", "zh-CN"));
    headers.add(new BasicHeader("Connection", "Keep-Alive"));
    httpClientBuilder.setDefaultHeaders(headers);
    HttpClient httpClient = httpClientBuilder.build();

    // httpClient連接配置,底層是配置RequestConfig
    HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
    // 連接超時
    clientHttpRequestFactory.setConnectTimeout(connectTimeout);
    // 數據讀取超時時間,即SocketTimeout
    clientHttpRequestFactory.setReadTimeout(readTimeout);
    // 連接不夠用的等待時間,不宜過長,必須設置,比如連接不夠用時,時間過長將是災難性的
    clientHttpRequestFactory.setConnectionRequestTimeout(connectionRequestTimeout);
    // 緩衝請求數據,默認值是true。通過POST或者PUT大量發送數據時,建議將此屬性更改為false,以免耗盡內存。
    if (!bufferRequestBody) {
        clientHttpRequestFactory.setBufferRequestBody(false);
    }
    // 添加內容轉換器
    // List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
    messageConverters.add(new FastJsonHttpMessageConverter());
    messageConverters.add(new StringHttpMessageConverter(Charset.forName(charset)));
    messageConverters.add(new ByteArrayHttpMessageConverter());
    super.setMessageConverters(messageConverters);
    super.setRequestFactory(clientHttpRequestFactory);
    super.setErrorHandler(new DefaultResponseErrorHandler());
}
 
開發者ID:geeker-lait,項目名稱:tasfe-framework,代碼行數:46,代碼來源:HttpClientTemplate.java

示例8: build

import org.apache.http.impl.client.HttpClientBuilder; //導入方法依賴的package包/類
/**
 * @param listener Log listener
 * @param prompt   Prompt for proxy credentials
 * @return Builder for HTTP client
 */
public HttpClientBuilder build(final TranscriptListener listener, final LoginCallback prompt) {
    final HttpClientBuilder configuration = HttpClients.custom();
    // Use HTTP Connect proxy implementation provided here instead of
    // relying on internal proxy support in socket factory
    final Proxy proxy = proxyFinder.find(host);
    switch(proxy.getType()) {
        case HTTP:
        case HTTPS:
            final HttpHost h = new HttpHost(proxy.getHostname(), proxy.getPort(), StringUtils.lowerCase(proxy.getType().name()));
            if(log.isInfoEnabled()) {
                log.info(String.format("Setup proxy %s", h));
            }
            configuration.setProxy(h);
            configuration.setProxyAuthenticationStrategy(new CallbackProxyAuthenticationStrategy(ProxyCredentialsStoreFactory.get(), host, prompt));
            break;
    }
    configuration.setUserAgent(new PreferencesUseragentProvider().get());
    final int timeout = preferences.getInteger("connection.timeout.seconds") * 1000;
    configuration.setDefaultSocketConfig(SocketConfig.custom()
        .setTcpNoDelay(true)
        .setSoTimeout(timeout)
        .build());
    configuration.setDefaultRequestConfig(this.createRequestConfig(timeout));
    final String encoding;
    if(null == host.getEncoding()) {
        encoding = preferences.getProperty("browser.charset.encoding");
    }
    else {
        encoding = host.getEncoding();
    }
    configuration.setDefaultConnectionConfig(ConnectionConfig.custom()
        .setBufferSize(preferences.getInteger("http.socket.buffer"))
        .setCharset(Charset.forName(encoding))
        .build());
    if(preferences.getBoolean("http.connections.reuse")) {
        configuration.setConnectionReuseStrategy(new DefaultClientConnectionReuseStrategy());
    }
    else {
        configuration.setConnectionReuseStrategy(new NoConnectionReuseStrategy());
    }
    configuration.setRetryHandler(new ExtendedHttpRequestRetryHandler(preferences.getInteger("http.connections.retry")));
    configuration.setServiceUnavailableRetryStrategy(new DisabledServiceUnavailableRetryStrategy());
    if(!preferences.getBoolean("http.compression.enable")) {
        configuration.disableContentCompression();
    }
    configuration.setRequestExecutor(new LoggingHttpRequestExecutor(listener));
    // Always register HTTP for possible use with proxy. Contains a number of protocol properties such as the
    // default port and the socket factory to be used to create the java.net.Socket instances for the given protocol
    configuration.setConnectionManager(this.createConnectionManager(this.createRegistry()));
    configuration.setDefaultAuthSchemeRegistry(RegistryBuilder.<AuthSchemeProvider>create()
        .register(AuthSchemes.BASIC, new BasicSchemeFactory(
            Charset.forName(preferences.getProperty("http.credentials.charset"))))
        .register(AuthSchemes.DIGEST, new DigestSchemeFactory(
            Charset.forName(preferences.getProperty("http.credentials.charset"))))
        .register(AuthSchemes.NTLM, new NTLMSchemeFactory())
        .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory())
        .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()).build());
    return configuration;
}
 
開發者ID:iterate-ch,項目名稱:cyberduck,代碼行數:65,代碼來源:HttpConnectionPoolBuilder.java

示例9: main

import org.apache.http.impl.client.HttpClientBuilder; //導入方法依賴的package包/類
public static void main(String[] args) throws Exception
{
   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);

   // 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!
   HttpClient client = b.build();

   HttpGet get = new HttpGet("https://cpj.org");
   //get.setFollowRedirects(true);

   HttpResponse response = client.execute(get);
   HttpEntity entity = response.getEntity();
   
   //if you got this far, you made it.

}
 
開發者ID:wellsb1,項目名稱:fort_w,代碼行數:45,代碼來源:TestHttpClient45IgnoreSSLErrors.java


注:本文中的org.apache.http.impl.client.HttpClientBuilder.setConnectionManager方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。