Java Code Examples for org.apache.http.impl.client.HttpClientBuilder#setConnectionManager()

The following examples show how to use org.apache.http.impl.client.HttpClientBuilder#setConnectionManager() . 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: ProcessConnection.java    From jasperreports with GNU Lesser General Public License v3.0 6 votes vote down vote up
public ProcessConnection(ProcessDirector director, PhantomJSProcess process)
{
	this.process = process;
	
	HttpClientBuilder clientBuilder = HttpClients.custom();
	
	// single connection
	BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager();
	clientBuilder.setConnectionManager(connManager);
	
	RequestConfig requestConfig = RequestConfig.custom()
			// ignore cookies for now
			.setCookieSpec(CookieSpecs.IGNORE_COOKIES)
			.setSocketTimeout(director.getRequestTimeout()).build();
	clientBuilder.setDefaultRequestConfig(requestConfig);
	
	this.httpClient = clientBuilder.build();
}
 
Example 2
Source File: HttpDataService.java    From jasperreports with GNU Lesser General Public License v3.0 6 votes vote down vote up
protected CloseableHttpClient createHttpClient(Map<String, Object> parameters)
{
	HttpClientBuilder clientBuilder = HttpClients.custom();
	
	// single connection
	BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager();
	clientBuilder.setConnectionManager(connManager);
	
	// ignore cookies for now
	RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();
	clientBuilder.setDefaultRequestConfig(requestConfig);
	
	setAuthentication(parameters, clientBuilder);
	
	CloseableHttpClient client = clientBuilder.build();
	return client;
}
 
Example 3
Source File: DefaultHttpClientConfigurer.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
 * Customizes the configuration of the httpClientBuilder.
 *
 * <p>Internally, this uses several helper methods to assist with configuring:
 * <ul>
 *     <li>Calls {@link #buildConnectionManager()} and sets the resulting {@link HttpClientConnectionManager} (if
 *     non-null) into the httpClientBuilder.</li>
 *     <li>Calls {@link #buildRequestConfig()} and sets the resulting {@link RequestConfig} (if non-null) into the
 *     httpClientBuilder.</li>
 *     <li>Calls {@link #buildRetryHandler()} and sets the resulting {@link HttpRequestRetryHandler} (if non-null)
 *     into the httpClientBuilder.</li>
 * </ul>
 * </p>
 *
 * @param httpClientBuilder the httpClientBuilder being configured
 */
@Override
public void customizeHttpClient(HttpClientBuilder httpClientBuilder) {

    HttpClientConnectionManager connectionManager = buildConnectionManager();
    if (connectionManager != null) {
        httpClientBuilder.setConnectionManager(connectionManager);
    }

    RequestConfig requestConfig = buildRequestConfig();
    if (requestConfig != null) {
        httpClientBuilder.setDefaultRequestConfig(requestConfig);
    }

    HttpRequestRetryHandler retryHandler = buildRetryHandler();
    if (retryHandler != null) {
        httpClientBuilder.setRetryHandler(retryHandler);
    }
}
 
Example 4
Source File: HttpConnectionUtil.java    From red5-server-common with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a client with all our selected properties / params.
 * 
 * @param timeout
 *            - socket timeout to set
 * @return client
 */
public static final HttpClient getClient(int timeout) {
    HttpClientBuilder client = HttpClientBuilder.create();
    // set the connection manager
    client.setConnectionManager(connectionManager);
    // dont retry
    client.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false));
    // establish a connection within x seconds
    RequestConfig config = RequestConfig.custom().setSocketTimeout(timeout).build();
    client.setDefaultRequestConfig(config);
    // no redirects
    client.disableRedirectHandling();
    // set custom ua
    client.setUserAgent(userAgent);
    // set the proxy if the user has one set
    if ((System.getProperty("http.proxyHost") != null) && (System.getProperty("http.proxyPort") != null)) {
        HttpHost proxy = new HttpHost(System.getProperty("http.proxyHost").toString(), Integer.valueOf(System.getProperty("http.proxyPort")));
        client.setProxy(proxy);
    }
    return client.build();
}
 
Example 5
Source File: WebServicesClient.java    From Bats with Apache License 2.0 5 votes vote down vote up
public WebServicesClient(ClientConfig config)
{
  if (SecurityUtils.isHadoopWebSecurityEnabled()) {
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    httpClientBuilder.setConnectionManager(connectionManager);
    httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    httpClientBuilder.setDefaultAuthSchemeRegistry(authRegistry);
    ApacheHttpClient4Handler httpClientHandler = new ApacheHttpClient4Handler(httpClientBuilder.build(), new BasicCookieStore(), false);
    client = new Client(httpClientHandler, config);
  } else {
    client = Client.create(config);
  }
}
 
Example 6
Source File: HttpClientManager.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
public CloseableHttpClient build() {
  HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
  httpClientBuilder.setConnectionManager( manager );

  RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
  if ( socketTimeout > 0 ) {
    requestConfigBuilder.setSocketTimeout( socketTimeout );
  }
  if ( connectionTimeout > 0 ) {
    requestConfigBuilder.setConnectTimeout( socketTimeout );
  }
  if ( proxy != null ) {
    requestConfigBuilder.setProxy( proxy );
  }
  if ( cookieSpec != null ) {
    requestConfigBuilder.setCookieSpec( cookieSpec );
  }
  if ( maxRedirects > 0 ) {
    requestConfigBuilder.setMaxRedirects( maxRedirects );
  }
  if ( allowCircularRedirects ) {
    requestConfigBuilder.setCircularRedirectsAllowed( true );
  }
  if ( !rejectRelativeRedirect ) {
    requestConfigBuilder.setRelativeRedirectsAllowed( true );
  }

  // RequestConfig built
  httpClientBuilder.setDefaultRequestConfig( requestConfigBuilder.build() );

  if ( provider != null ) {
    httpClientBuilder.setDefaultCredentialsProvider( provider );
  }
  if ( redirectStrategy != null ) {
    httpClientBuilder.setRedirectStrategy( redirectStrategy );
  }

  return httpClientBuilder.build();
}
 
Example 7
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 8
Source File: HttpClientConfiguration.java    From interface-test with Apache License 2.0 5 votes vote down vote up
@Bean(name = "defaultHttpClient")
@ConditionalOnMissingBean
public HttpClient httpClient() {
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setConnectionManager(httpClientConnectionManager());

    return builder.build();
}
 
Example 9
Source File: HttpClientGenerator.java    From webmagic with Apache License 2.0 5 votes vote down vote up
private CloseableHttpClient generateClient(Site site) {
    HttpClientBuilder httpClientBuilder = HttpClients.custom();

    httpClientBuilder.setConnectionManager(connectionManager);
    if (site.getUserAgent() != null) {
        httpClientBuilder.setUserAgent(site.getUserAgent());
    } else {
        httpClientBuilder.setUserAgent("");
    }
    if (site.isUseGzip()) {
        httpClientBuilder.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");
                }
            }
        });
    }
    //解决post/redirect/post 302跳转问题
    httpClientBuilder.setRedirectStrategy(new CustomRedirectStrategy());

    SocketConfig.Builder socketConfigBuilder = SocketConfig.custom();
    socketConfigBuilder.setSoKeepAlive(true).setTcpNoDelay(true);
    socketConfigBuilder.setSoTimeout(site.getTimeOut());
    SocketConfig socketConfig = socketConfigBuilder.build();
    httpClientBuilder.setDefaultSocketConfig(socketConfig);
    connectionManager.setDefaultSocketConfig(socketConfig);
    httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(site.getRetryTimes(), true));
    generateCookie(httpClientBuilder, site);
    return httpClientBuilder.build();
}
 
Example 10
Source File: HttpFetch.java    From activitystreams with Apache License 2.0 5 votes vote down vote up
private CloseableHttpClient initClient(Builder builder) {
  HttpClientBuilder b = builder.builder;
  b.setConnectionManager(manager);
  ImmutableSet<Header> headers = 
    builder.defaultHeaders.build();
  if (!headers.isEmpty())
    b.setDefaultHeaders(headers);
  if (builder.userAgent != null)
    b.setUserAgent(builder.userAgent);
  return b.build();
}
 
Example 11
Source File: HTTPInvoker.java    From product-iots 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 12
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 13
Source File: HttpUtil.java    From codehelper.generator with Apache License 2.0 4 votes vote down vote up
public static void init() throws RuntimeException {
        try {
            logger.warn(NOTICELINE + " httpUtil init begin " + NOTICELINE);
            SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
//            sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            sslContextBuilder.loadTrustMaterial(null,new TrustAnyTrustManager());
            SSLConnectionSocketFactory sslConnectionSocketFactory =
                    new SSLConnectionSocketFactory(
                            sslContextBuilder.build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

            Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().
                    register("http", new PlainConnectionSocketFactory()).
                    register("https", sslConnectionSocketFactory).
                    build();


            logger.warn(NOTICELINE + " SSL context init done " + NOTICELINE);

            //init connectionManager , ThreadSafe pooled conMgr
            PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(registry);
            poolingHttpClientConnectionManager.setMaxTotal(30);
            poolingHttpClientConnectionManager.setDefaultMaxPerRoute(3);
            //init request config. pooltimeout,sotime,contimeout
            RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(POOL_TIMECOUT).setConnectTimeout(CON_TIMEOUT).setSocketTimeout(SO_TIMEOUT).build();
            // begin construct httpclient
            HttpClientBuilder httpClientBuilder = HttpClients.custom();
            httpClientBuilder.setConnectionManager(poolingHttpClientConnectionManager);
            httpClientBuilder.setDefaultRequestConfig(requestConfig);
            httpClientBuilder.setRetryHandler(new HttpRequestRetryHandler() {
                @Override
                public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
                    if (executionCount >= HTTP_RETRY_COUNT) {
                        return false;
                    }
                    if (exception instanceof InterruptedIOException) {
                        // Timeout
                        logger.warn("httpUtil retry for InterruptIOException");
                        return true;
                    }
                    if (exception instanceof UnknownHostException) {
                        // Unknown host
                        return false;
                    }
                    if (exception instanceof SSLException) {
                        // SSL handshake exception
                        return false;
                    }
                    HttpClientContext clientContext = HttpClientContext.adapt(context);
                    HttpRequest request = clientContext.getRequest();
                    boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
                    if (idempotent) {
                        // Retry if the request is considered idempotent
                        logger.warn("httpUtil retry for idempotent");
                        return true;
                    }
                    return false;
                }
            });
            logger.warn(NOTICELINE + " poolManager , requestconfig init done " + NOTICELINE);

            httpclient = httpClientBuilder.build();
            logger.warn(NOTICELINE + " httpUtil init done " + NOTICELINE);
        } catch (Exception e) {
            logger.error(NOTICELINE + "httpclient init fail" + NOTICELINE, e);
            throw new RuntimeException(e);
        }
    }
 
Example 14
Source File: HTTPConnections.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public void setClientManager(HttpClientBuilder cb, HTTPMethod method) {
  HttpClientConnectionManager mgr = newManager(method);
  cb.setConnectionManager(mgr);
}
 
Example 15
Source File: HttpClientUtils.java    From ais-sdk with Apache License 2.0 4 votes vote down vote up
public static CloseableHttpClient acceptsUntrustedCertsHttpClient(boolean withProxy, ProxyHostInfo hostInfo, int connectionTimeout, int connectionRequestTimeout, int socketTimeout)
		throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
	HttpClientBuilder b = HttpClientBuilder.create();
	
	/**
	 * set http proxy
	 */
	
	b.setDefaultRequestConfig( 
			RequestConfig.custom().setConnectTimeout(connectionTimeout).setConnectionRequestTimeout(connectionRequestTimeout).setSocketTimeout(socketTimeout).build()
			);
	
	if(withProxy){
		HttpHost proxy=new HttpHost(hostInfo.getHostName(),hostInfo.getPort());
		b.setProxy(proxy);
		CredentialsProvider credsProvider = new BasicCredentialsProvider();
		credsProvider.setCredentials(
				new AuthScope(proxy.getHostName(), proxy.getPort()),
				new UsernamePasswordCredentials(hostInfo.getUserName(), hostInfo.getPassword()));
		b.setDefaultCredentialsProvider(credsProvider);
	}
	
	SSLContext sslContext = new SSLContextBuilder().useProtocol("TLSv1.2").loadTrustMaterial(null, new TrustStrategy() {
		public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
			return true;
		}
	}).build();
	b.setSSLContext(sslContext);
	b.setConnectionTimeToLive(180, TimeUnit.SECONDS);

	HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;

	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);
	connMgr.setMaxTotal(200);
	connMgr.setDefaultMaxPerRoute(100);
	b.setConnectionManager(connMgr);
	CloseableHttpClient client = b.build();
	return client;
}
 
Example 16
Source File: HttpClientUtils.java    From ais-sdk with Apache License 2.0 4 votes vote down vote up
public static CloseableHttpClient acceptsUntrustedCertsHttpClient(boolean withProxy, ProxyHostInfo hostInfo, int connectionTimeout, int connectionRequestTimeout, int socketTimeout)
		throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
	HttpClientBuilder b = HttpClientBuilder.create();
	
	/**
	 * set http proxy
	 */
	
	b.setDefaultRequestConfig( 
			RequestConfig.custom().setConnectTimeout(connectionTimeout).setConnectionRequestTimeout(connectionRequestTimeout).setSocketTimeout(socketTimeout).build()
			);
	
	if(withProxy){
		HttpHost proxy=new HttpHost(hostInfo.getHostName(),hostInfo.getPort());
		b.setProxy(proxy);
		CredentialsProvider credsProvider = new BasicCredentialsProvider();
		credsProvider.setCredentials(
				new AuthScope(proxy.getHostName(), proxy.getPort()),
				new UsernamePasswordCredentials(hostInfo.getUserName(), hostInfo.getPassword()));
		b.setDefaultCredentialsProvider(credsProvider);
	}
	
	SSLContext sslContext = new SSLContextBuilder().useProtocol("TLSv1.2").loadTrustMaterial(null, new TrustStrategy() {
		public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
			return true;
		}
	}).build();
	b.setSSLContext(sslContext);
	b.setConnectionTimeToLive(180, TimeUnit.SECONDS);

	HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;

	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);
	connMgr.setMaxTotal(200);
	connMgr.setDefaultMaxPerRoute(100);
	b.setConnectionManager(connMgr);
	CloseableHttpClient client = b.build();
	return client;
}
 
Example 17
Source File: HttpClient.java    From utils with Apache License 2.0 4 votes vote down vote up
protected HttpClient() {
    proxies = new ArrayList<HttpHost>();

    HttpClientBuilder builder = HttpClientBuilder.create();

    SSLContext sslContext;
    try {
        sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        }).build();
    } catch (Exception e) {
        e.printStackTrace(System.err);
        System.exit(0);
        return;
    }

    builder.setSSLContext(sslContext);
    HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
    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);
    connMgr.setMaxTotal(500);
    connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());
    builder.setConnectionManager(connMgr);

    config = RequestConfig.custom()
            .setCookieSpec(CookieSpecs.DEFAULT)
            .build();
    builder.setDefaultRequestConfig(config);

    cookieStore = new BasicCookieStore();
    builder.setDefaultCookieStore(cookieStore);
    client = builder.build();

    connectTimeout = DEFAULT_CONNECTION_TIMEOUT;
    soTimeout = DEFAULT_SO_TIMEOUT;
}
 
Example 18
Source File: HttpClientUtils.java    From turbo-rpc with Apache License 2.0 4 votes vote down vote up
public static CloseableHttpClient createHttpClient(int concurrency) {
	HttpClientBuilder builder = HttpClientBuilder.create();

	PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
	connManager.setDefaultMaxPerRoute(concurrency);
	connManager.setMaxTotal(concurrency);

	RequestConfig requestConfig = RequestConfig.custom()//
			.setAuthenticationEnabled(true)//
			.setSocketTimeout(SOCKET_TIMEOUT)//
			.setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT)//
			.setConnectTimeout(CONNECT_TIMEOUT)//
			.setRedirectsEnabled(true)//
			.setRelativeRedirectsAllowed(true)//
			.setMaxRedirects(15)//
			.build();

	SocketConfig socketConfig = SocketConfig.custom()//
			.setSoKeepAlive(true)//
			.setSoReuseAddress(true)//
			.build();

	CookieSpecProvider cookieSpecProvider = new IgnoreSpecProvider();
	Lookup<CookieSpecProvider> cookieSpecRegistry = RegistryBuilder.<CookieSpecProvider>create()//
			.register(CookieSpecs.DEFAULT, cookieSpecProvider)//
			.register(CookieSpecs.STANDARD, cookieSpecProvider)//
			.register(CookieSpecs.STANDARD_STRICT, cookieSpecProvider)//
			.build();

	builder.setConnectionManager(connManager);
	builder.setDefaultSocketConfig(socketConfig);
	builder.setDefaultRequestConfig(requestConfig);
	builder.setDefaultCookieSpecRegistry(cookieSpecRegistry);

	return builder.addInterceptorLast((HttpRequest request, HttpContext context) -> {
		request.removeHeaders("Host");
		request.removeHeaders("Accept-Encoding");
		//request.removeHeaders("Connection");
		request.removeHeaders("User-Agent");
	}).build();
}
 
Example 19
Source File: HttpClientFactory.java    From vividus with Apache License 2.0 4 votes vote down vote up
@Override
public IHttpClient buildHttpClient(HttpClientConfig config)
{
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setDefaultHeaders(config.createHeaders());
    if (config.hasCookieStore())
    {
        builder.setDefaultCookieStore(config.getCookieStore());
    }
    if (config.hasCredentials())
    {
        AuthScope authScope = config.hasAuthScope() ? config.getAuthScope()
                : ClientBuilderUtils.DEFAULT_AUTH_SCOPE;
        CredentialsProvider credProvider = ClientBuilderUtils.createCredentialsProvider(authScope,
                config.getCredentials());
        builder.setDefaultCredentialsProvider(credProvider);
    }

    sslContextFactory.getSslContext(SSLConnectionSocketFactory.SSL, !config.isSslCertificateCheckEnabled())
            .ifPresent(builder::setSSLContext);

    if (!config.isSslHostnameVerificationEnabled())
    {
        builder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE);
    }
    builder.setConnectionManager(config.getConnectionManager());
    builder.setMaxConnTotal(config.getMaxTotalConnections());
    builder.setMaxConnPerRoute(config.getMaxConnectionsPerRoute());
    builder.addInterceptorLast(config.getLastRequestInterceptor());
    builder.addInterceptorLast(config.getLastResponseInterceptor());
    builder.setRedirectStrategy(config.getRedirectStrategy());
    builder.setRetryHandler(config.getHttpRequestRetryHandler());
    Builder requestConfigBuilder = RequestConfig.custom();
    requestConfigBuilder.setConnectionRequestTimeout(config.getConnectionRequestTimeout());
    requestConfigBuilder.setConnectTimeout(config.getConnectTimeout());
    requestConfigBuilder.setCircularRedirectsAllowed(config.isCircularRedirectsAllowed());
    requestConfigBuilder.setSocketTimeout(config.getSocketTimeout());
    Optional.ofNullable(config.getCookieSpec()).ifPresent(requestConfigBuilder::setCookieSpec);
    builder.setDefaultRequestConfig(requestConfigBuilder.build());
    builder.setDefaultSocketConfig(SocketConfig.copy(SocketConfig.DEFAULT)
            .setSoTimeout(config.getSocketTimeout())
            .build());
    builder.setDnsResolver(config.getDnsResolver());

    HttpClient httpClient = new HttpClient();
    httpClient.setCloseableHttpClient(builder.build());
    if (config.hasBaseUrl())
    {
        httpClient.setHttpHost(HttpHost.create(config.getBaseUrl()));
    }
    httpClient.setSkipResponseEntity(config.isSkipResponseEntity());
    return httpClient;
}
 
Example 20
Source File: RestTemplateConfig.java    From plumdo-work with Apache License 2.0 3 votes vote down vote up
@Bean
public HttpClient httpClient() {
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    httpClientBuilder.setSSLContext(sslContext());

    httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(2, true));

    httpClientBuilder.setConnectionManager(poolingHttpClientConnectionManager());

    return httpClientBuilder.build();
}