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

The following examples show how to use org.apache.http.impl.client.HttpClientBuilder#setConnectionTimeToLive() . These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: bird-java   File: HttpClient.java    License: MIT License 6 votes vote down vote up
public static HttpResult httpPost(String url, Map<String, String> headers, String content) {
    try {
        HttpClientBuilder builder = HttpClients.custom();
        builder.setConnectionTimeToLive(500, TimeUnit.MILLISECONDS);

        CloseableHttpClient httpClient = builder.build();
        HttpPost httpost = new HttpPost(url);

        if(headers != null){
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpost.setHeader(entry.getKey(), entry.getValue());
            }
        }

        httpost.setEntity(new StringEntity(content, ContentType.create("application/json", DEFAULT_CONTENT_TYPE)));
        HttpResponse response = httpClient.execute(httpost);
        HttpEntity entity = response.getEntity();

        Reader reader = new InputStreamReader(entity.getContent(), DEFAULT_CONTENT_TYPE);
        CharArrayWriter sw = new CharArrayWriter();
        copy(reader, sw);
        return new HttpResult(response.getStatusLine().getStatusCode(), sw.toString(), Collections.emptyMap());
    } catch (Exception e) {
        return new HttpResult(500, e.toString(), Collections.emptyMap());
    }
}
 
Example 2
Source Project: htmlunit   File: HttpWebConnection.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * React on changes that may have occurred on the WebClient settings.
 * Registering as a listener would be probably better.
 */
private HttpClientBuilder reconfigureHttpClientIfNeeded(final HttpClientBuilder httpClientBuilder) {
    final WebClientOptions options = webClient_.getOptions();

    // register new SSL factory only if settings have changed
    if (options.isUseInsecureSSL() != usedOptions_.isUseInsecureSSL()
            || options.getSSLClientCertificateStore() != usedOptions_.getSSLClientCertificateStore()
            || options.getSSLTrustStore() != usedOptions_.getSSLTrustStore()
            || options.getSSLClientCipherSuites() != usedOptions_.getSSLClientCipherSuites()
            || options.getSSLClientProtocols() != usedOptions_.getSSLClientProtocols()
            || options.getProxyConfig() != usedOptions_.getProxyConfig()) {
        configureHttpsScheme(httpClientBuilder);

        if (connectionManager_ != null) {
            connectionManager_.shutdown();
            connectionManager_ = null;
        }
    }

    final int timeout = getTimeout();
    if (timeout != usedOptions_.getTimeout()) {
        configureTimeout(httpClientBuilder, timeout);
    }

    final long connectionTimeToLive = webClient_.getOptions().getConnectionTimeToLive();
    if (connectionTimeToLive != usedOptions_.getConnectionTimeToLive()) {
        httpClientBuilder.setConnectionTimeToLive(connectionTimeToLive, TimeUnit.MILLISECONDS);
        usedOptions_.setConnectionTimeToLive(connectionTimeToLive);
    }

    if (connectionManager_ == null) {
        connectionManager_ = createConnectionManager(httpClientBuilder);
    }
    httpClientBuilder.setConnectionManager(connectionManager_);

    return httpClientBuilder;
}
 
Example 3
@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 4
@Override
public PooledObject<CloseableHttpClient> makeObject() throws Exception {
    RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(connectionRequestTimeout)
            .setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).build();
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setDefaultRequestConfig(requestConfig);
    builder.setConnectionTimeToLive(connectionTimeToLive, TimeUnit.MILLISECONDS);
    return new DefaultPooledObject<>(builder.build());
}
 
Example 5
Source Project: ais-sdk   File: HttpClientUtils.java    License: 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 6
Source Project: ais-sdk   File: HttpClientUtils.java    License: 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 7
Source Project: vespa   File: ApacheGatewayConnection.java    License: Apache License 2.0 4 votes vote down vote up
public HttpClient createClient() {
    HttpClientBuilder clientBuilder;
    if (connectionParams.useTlsConfigFromEnvironment()) {
        clientBuilder = VespaHttpClientBuilder.create();
    } else {
        clientBuilder = HttpClientBuilder.create();
        if (connectionParams.getSslContext() != null) {
            setSslContext(clientBuilder, connectionParams.getSslContext());
        } else {
            SslContextBuilder builder = new SslContextBuilder();
            if (connectionParams.getPrivateKey() != null && connectionParams.getCertificate() != null) {
                builder.withKeyStore(connectionParams.getPrivateKey(), connectionParams.getCertificate());
            }
            if (connectionParams.getCaCertificates() != null) {
                builder.withTrustStore(connectionParams.getCaCertificates());
            }
            setSslContext(clientBuilder, builder.build());
        }
        if (connectionParams.getHostnameVerifier() != null) {
            clientBuilder.setSSLHostnameVerifier(connectionParams.getHostnameVerifier());
        }
        clientBuilder.setUserTokenHandler(context -> null); // https://stackoverflow.com/a/42112034/1615280
    }
    clientBuilder.setMaxConnPerRoute(1);
    clientBuilder.setMaxConnTotal(1);
    clientBuilder.setConnectionTimeToLive(connectionParams.getConnectionTimeToLive().getSeconds(), TimeUnit.SECONDS);
    clientBuilder.setUserAgent(String.format("vespa-http-client (%s)", Vtag.currentVersion));
    clientBuilder.setDefaultHeaders(Collections.singletonList(new BasicHeader(Headers.CLIENT_VERSION, Vtag.currentVersion)));
    clientBuilder.disableContentCompression();
    // Try to disable the disabling to see if system tests become stable again.
    // clientBuilder.disableAutomaticRetries();
    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
    requestConfigBuilder.setSocketTimeout(0);
    if (connectionParams.getProxyHost() != null) {
        requestConfigBuilder.setProxy(new HttpHost(connectionParams.getProxyHost(), connectionParams.getProxyPort()));
    }
    clientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());

    log.fine("Creating HttpClient: " + " ConnectionTimeout "
                    + " SocketTimeout 0 secs "
                    + " proxyhost (can be null) " + connectionParams.getProxyHost()
                    + ":" + connectionParams.getProxyPort()
                    + (useSsl ? " using ssl " : " not using ssl")
    );
    return clientBuilder.build();
}
 
Example 8
private HttpConnection(final HostDescription host, final Integer timeout, final String user, final String password,
                       final Boolean useSsl, final SSLContext sslContext, final ArangoSerialization util, final Protocol contentType,
                       final Long ttl, final String httpCookieSpec) {
    super();
    this.host = host;
    this.user = user;
    this.password = password;
    this.useSsl = useSsl;
    this.util = util;
    this.contentType = contentType;
    final RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder
            .create();
    if (Boolean.TRUE == useSsl) {
        if (sslContext != null) {
            registryBuilder.register("https", new SSLConnectionSocketFactory(sslContext));
        } else {
            registryBuilder.register("https", new SSLConnectionSocketFactory(SSLContexts.createSystemDefault()));
        }
    } else {
        registryBuilder.register("http", new PlainConnectionSocketFactory());
    }
    cm = new PoolingHttpClientConnectionManager(registryBuilder.build());
    cm.setDefaultMaxPerRoute(1);
    cm.setMaxTotal(1);
    final RequestConfig.Builder requestConfig = RequestConfig.custom();
    if (timeout != null && timeout >= 0) {
        requestConfig.setConnectTimeout(timeout);
        requestConfig.setConnectionRequestTimeout(timeout);
        requestConfig.setSocketTimeout(timeout);
    }

    if (httpCookieSpec != null && httpCookieSpec.length() > 1) {
        requestConfig.setCookieSpec(httpCookieSpec);
    }

    final ConnectionKeepAliveStrategy keepAliveStrategy = (response, context) -> HttpConnection.this.getKeepAliveDuration(response);
    final HttpClientBuilder builder = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig.build())
            .setConnectionManager(cm).setKeepAliveStrategy(keepAliveStrategy)
            .setRetryHandler(new DefaultHttpRequestRetryHandler());
    if (ttl != null) {
        builder.setConnectionTimeToLive(ttl, TimeUnit.MILLISECONDS);
    }
    client = builder.build();
}