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

The following examples show how to use org.apache.http.impl.client.HttpClientBuilder#setDefaultRequestConfig() . 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
private void initImpl() {
	synchronized (this) {
		if (impl == null) {
			HttpClientBuilder builder = HttpClients.custom();

			if (receiveTimeout != null) {
				RequestConfig.Builder requestBuilder = RequestConfig.custom();
				requestBuilder = requestBuilder.setSocketTimeout(receiveTimeout);
				builder.setDefaultRequestConfig(requestBuilder.build());
			}

			for (HttpClientAdapterListener listener : listeners) {
				listener.onBuild(builder);
			}
			impl = builder.build();
		}
	}
}
 
Example 2
Source Project: hbase   File: ThriftConnection.java    License: Apache License 2.0 6 votes vote down vote up
public synchronized HttpClient getHttpClient() {
  if (httpClient != null) {
    return httpClient;
  }
  int retry = conf.getInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER,
      HConstants.DEFAULT_HBASE_CLIENT_RETRIES_NUMBER);
  long pause = conf.getLong(HConstants.HBASE_CLIENT_PAUSE, 5);
  HttpClientBuilder builder = HttpClientBuilder.create();
  RequestConfig.Builder requestBuilder = RequestConfig.custom();
  requestBuilder = requestBuilder.setConnectTimeout(getConnectTimeout());
  requestBuilder = requestBuilder.setSocketTimeout(getOperationTimeout());
  builder.setRetryHandler(new DelayRetryHandler(retry, pause));
  builder.setDefaultRequestConfig(requestBuilder.build());
  httpClient = builder.build();
  httpClientCreated = true;
  return httpClient;
}
 
Example 3
/**
 * Returns a client with all our selected properties / params and SSL enabled.
 * 
 * @return client
 */
public static final HttpClient getSecureClient() {
    HttpClientBuilder client = HttpClientBuilder.create();
    // set the ssl verifier to accept all
    client.setSSLHostnameVerifier(new NoopHostnameVerifier());
    // 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(connectionTimeout).build();
    client.setDefaultRequestConfig(config);
    // no redirects
    client.disableRedirectHandling();
    // set custom ua
    client.setUserAgent(userAgent);
    return client.build();
}
 
Example 4
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 5
@Override
protected CloseableHttpClient getClient(boolean useSSL, String url,
    Map<String, String> stringHeaders, int socketTimeout) {
  HttpClientBuilder cb = super.getClientBuilder(useSSL, url, stringHeaders, socketTimeout);
  ElasticSearchTransportConfig config = (ElasticSearchTransportConfig) super.config;

  if (config.getAuthConfig() != null) {
    if (config.getAuthConfig() instanceof BasicHttpAuthConfig) {
      cb = addUserPassAuth(cb, (BasicHttpAuthConfig) config.getAuthConfig());
    } else if (config.getAuthConfig() instanceof UrlSigningAuthConfig) {
      cb = addSigningAuth(cb, (UrlSigningAuthConfig) config.getAuthConfig());
    }
  }

  RequestConfig rc = RequestConfig.custom().setConnectTimeout(5000)
      .setSocketTimeout(config.getTimeout()).build();
  cb.setDefaultRequestConfig(rc);

  return cb.build();
}
 
Example 6
public static String getFileInfo(String baseUrl, String externalId, String receiverAddress, String urkundUsername, String urkundPassword, int timeout){
	String ret = null;
	RequestConfig.Builder requestBuilder = RequestConfig.custom();
	requestBuilder = requestBuilder.setConnectTimeout(timeout);
	requestBuilder = requestBuilder.setConnectionRequestTimeout(timeout);
	
	HttpClientBuilder builder = HttpClientBuilder.create();     
	builder.setDefaultRequestConfig(requestBuilder.build());
	try (CloseableHttpClient httpClient = builder.build()) {
		HttpGet httpget = new HttpGet(baseUrl+"submissions/"+receiverAddress+"/"+externalId);
		
		//------------------------------------------------------------
		if(StringUtils.isNotBlank(urkundUsername) && StringUtils.isNotBlank(urkundPassword)) {
			addAuthorization(httpget, urkundUsername, urkundPassword);
		}
		//------------------------------------------------------------
		httpget.addHeader("Accept", "application/json");
		//------------------------------------------------------------
		
		HttpResponse response = httpClient.execute(httpget);
		HttpEntity resEntity = response.getEntity();

		if (resEntity != null) {
			ret = EntityUtils.toString(resEntity);
			EntityUtils.consume(resEntity);
		}
		
	} catch (IOException e) {
		log.error("ERROR getting File Info : ", e);
	}
	return ret;
}
 
Example 7
protected HttpClientBuilder clientBuilder(final URL nexusUrl, final boolean useCredentials) throws Exception {
  HttpClientBuilder builder = HttpClients.custom();
  builder.setDefaultRequestConfig(requestConfig());
  if (useCredentials) {
    doUseCredentials(nexusUrl, builder);
  }
  builder.setSSLSocketFactory(sslSocketFactory());
  return builder;
}
 
Example 8
/**
 * Set connect and read timeouts for an HTTP client that is being built.
 *
 * @param builder
 *         The client builder to which timeouts will be applied.
 */
private void applyTimeouts(final HttpClientBuilder builder) {
    final RequestConfig requestConfig =
            RequestConfig
                    .custom()
                    .setConnectionRequestTimeout(this.connectTimeout)
                    .setConnectTimeout(this.connectTimeout)
                    .setSocketTimeout(this.readTimeout)
                    .build();

    builder.setDefaultRequestConfig(requestConfig);
}
 
Example 9
Source Project: x-pipe   File: CtripSSOFilter.java    License: Apache License 2.0 5 votes vote down vote up
private void initHttpClient() {

        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
        connManager.setMaxTotal(20);
        connManager.setDefaultMaxPerRoute(connManager.getMaxTotal());
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().setConnectionManager(connManager);

        httpClientBuilder.setDefaultRequestConfig(
                RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).setConnectionRequestTimeout(3000).build()
        );

        httpClient = httpClientBuilder.build();
    }
 
Example 10
Source Project: roncoo-pay   File: HttpClientUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static HttpClient getHttpClient(){
    RequestConfig.Builder configBuilder = RequestConfig.custom();
    configBuilder.setConnectTimeout(CONNECT_TIME_OUT);
    configBuilder.setSocketTimeout(SOCKET_TIME_OUT);

    HttpClientBuilder clientBuilder = HttpClients.custom();
    clientBuilder.setDefaultRequestConfig(configBuilder.build());
    HttpClient httpClient = clientBuilder.build();

    return httpClient;
}
 
Example 11
public void initialize(ThunderProperties properties, boolean https) throws Exception {
    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(properties.getInteger(ThunderConstant.APACHE_CONNECT_TIMEOUT_ATTRIBUTE_NAME))
            .setConnectionRequestTimeout(properties.getInteger(ThunderConstant.APACHE_CONNECT_TIMEOUT_ATTRIBUTE_NAME))
            .setSocketTimeout(properties.getInteger(ThunderConstant.APACHE_SO_TIMEOUT_ATTRIBUTE_NAME))
            .build();

    HttpClientBuilder clientBuilder = HttpClients.custom();
    clientBuilder.setDefaultRequestConfig(requestConfig);

    if (https) {
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }

        }).build();
        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);

        clientBuilder.setSSLSocketFactory(sslConnectionSocketFactory);
    }

    httpSyncClient = clientBuilder.build();

    LOG.info("Create apache sync client with {} successfully", https ? "https mode" : "http mode");
}
 
Example 12
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 13
public static CloseableHttpClient create(RequestConfig config, HttpRequestRetryHandler retryHandler, HttpClientConnectionManager connectionManager) {
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.useSystemProperties().setRedirectStrategy(AlwaysRedirectStrategy.DEFAULT).addInterceptorLast(new RequestContent(true));
    if (config != null)
        builder.setDefaultRequestConfig(config);
    if (retryHandler != null)
        builder.setRetryHandler(retryHandler);
    if (connectionManager != null)
        builder.setConnectionManager(connectionManager);
    return builder.build();
}
 
Example 14
Source Project: vespa   File: VespaHttpClient.java    License: Apache License 2.0 5 votes vote down vote up
private HttpClient createClient(VespaConfiguration configuration) {
    HttpClientBuilder clientBuilder = HttpClientBuilder.create();

    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
    if (configuration != null) {
        requestConfigBuilder.setSocketTimeout(configuration.queryConnectionTimeout());
        requestConfigBuilder.setConnectTimeout(configuration.queryConnectionTimeout());
        if (configuration.proxyHost() != null) {
            requestConfigBuilder.setProxy(new HttpHost(configuration.proxyHost(), configuration.proxyPort()));
        }
    }
    clientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());
    return clientBuilder.build();
}
 
Example 15
Source Project: rpc-benchmark   File: HttpClientUtils.java    License: Apache License 2.0 5 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();

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

	return builder.build();
}
 
Example 16
static ClientHttpRequestFactory usingHttpComponents(ClientOptions options, SslConfiguration sslConfiguration)
		throws GeneralSecurityException, IOException {

	HttpClientBuilder httpClientBuilder = HttpClients.custom();

	httpClientBuilder.setRoutePlanner(
			new SystemDefaultRoutePlanner(DefaultSchemePortResolver.INSTANCE, ProxySelector.getDefault()));

	if (hasSslConfiguration(sslConfiguration)) {

		SSLContext sslContext = getSSLContext(sslConfiguration, getTrustManagers(sslConfiguration));
		SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);
		httpClientBuilder.setSSLSocketFactory(sslSocketFactory);
		httpClientBuilder.setSSLContext(sslContext);
	}

	RequestConfig requestConfig = RequestConfig.custom()
			//
			.setConnectTimeout(Math.toIntExact(options.getConnectionTimeout().toMillis())) //
			.setSocketTimeout(Math.toIntExact(options.getReadTimeout().toMillis())) //
			.setAuthenticationEnabled(true) //
			.build();

	httpClientBuilder.setDefaultRequestConfig(requestConfig);

	// Support redirects
	httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy());

	return new HttpComponentsClientHttpRequestFactory(httpClientBuilder.build());
}
 
Example 17
Source Project: vividus   File: HttpClientFactory.java    License: 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 18
/**
 * This method initialize CloseableHttpClient
 *
 */
private void initialize() {

	// accept snake oil
	boolean customClientInUse = false;

	if (useHttps && acceptSelfSigned) {

		SSLContext sslcontext = null;
		try {
			sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
		} catch (Exception e) {
			logger.warning("Exception during configuration of SSL for Agent Connector. Reverting to HTTP. "
					+ "Exception message: " + e.getMessage());
		}

		if (sslcontext != null) {

			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext); 

			// create request config builder
			RequestConfig.Builder requestBuilder = RequestConfig.custom();
			requestBuilder = requestBuilder.setConnectTimeout(agentTimeout * 1000);

			// create client builder
			HttpClientBuilder clientBuilder = HttpClients.custom(); 

			// set request configuration
			clientBuilder.setDefaultRequestConfig(requestBuilder.build());
			clientBuilder.setSSLSocketFactory(sslsf);

			httpClient = clientBuilder.build();

			Unirest.setHttpClient(httpClient);

			customClientInUse = true;
		}
	}

	if (!customClientInUse) {
		// set timeouts - we are not using custom client, we have to do it this way
		Unirest.setTimeouts(agentTimeout * 1000, agentTimeout * 1000);
	}
}
 
Example 19
public static String postDocument(String baseUrl, String receiverAddress, String externalId, UrkundSubmission submission, String urkundUsername, String urkundPassword, int timeout){
		String ret = null;
		
		RequestConfig.Builder requestBuilder = RequestConfig.custom();
		requestBuilder = requestBuilder.setConnectTimeout(timeout);
		requestBuilder = requestBuilder.setConnectionRequestTimeout(timeout);
		
		HttpClientBuilder builder = HttpClientBuilder.create();     
		builder.setDefaultRequestConfig(requestBuilder.build());
		try (CloseableHttpClient httpClient = builder.build()) {
			
			
			HttpPost httppost = new HttpPost(baseUrl+"submissions/"+receiverAddress+"/"+externalId);
			//------------------------------------------------------------
			EntityBuilder eBuilder = EntityBuilder.create();
			eBuilder.setBinary(submission.getContent());

			httppost.setEntity(eBuilder.build());
			//------------------------------------------------------------
			if(StringUtils.isNotBlank(urkundUsername) && StringUtils.isNotBlank(urkundPassword)) {
				addAuthorization(httppost, urkundUsername, urkundPassword);
			}
			//------------------------------------------------------------
			httppost.addHeader("Accept", "application/json");
			httppost.addHeader("Content-Type", submission.getMimeType());
			httppost.addHeader("Accept-Language", submission.getLanguage());
			httppost.addHeader("x-urkund-filename", submission.getFilenameEncoded());
			httppost.addHeader("x-urkund-submitter", submission.getSubmitterEmail());
			httppost.addHeader("x-urkund-anonymous", Boolean.toString(submission.isAnon()));
			httppost.addHeader("x-urkund-subject", submission.getSubject());
			httppost.addHeader("x-urkund-message", submission.getMessage());
			//------------------------------------------------------------

			HttpResponse response = httpClient.execute(httppost);
			HttpEntity resEntity = response.getEntity();

			if (resEntity != null) {
				ret = EntityUtils.toString(resEntity);
				EntityUtils.consume(resEntity);
			}

		} catch (IOException e) {
			log.error("ERROR uploading File : ", e);
		}
		
		
		return ret;
}
 
Example 20
/**
 * Initialization method.  This takes in the configuration and sets up the underlying
 * http client appropriately.
 * @param configuration The user defined configuration.
 */
@Override
public void init(final Configuration configuration) {
    // Save reference to configuration
    this.configuration = configuration;

    // Load RequestMutator instance from configuration.
    requestInterceptor = configuration.getRequestInterceptor();

    // Create default SSLContext
    final SSLContext sslcontext = SSLContexts.createDefault();

    // Initialize ssl context with configured key and trust managers.
    try {
        sslcontext.init(new KeyManager[0], getTrustManagers(), new SecureRandom());
    } catch (final KeyManagementException exception) {
        throw new RuntimeException(exception.getMessage(), exception);
    }

    // Create hostname verifier instance.
    final HostnameVerifier hostnameVerifier;
    // Emit an warning letting everyone know we're using an insecure configuration.
    if (configuration.getIgnoreInvalidSslCertificates()) {
        logger.warn("Using insecure configuration, skipping server-side certificate validation checks.");

        // If we're configured to ignore invalid certificates, use the Noop verifier.
        hostnameVerifier = NoopHostnameVerifier.INSTANCE;
    } else {
        // Use default implementation
        hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier();
    }

    // Allow TLSv1_1 and TLSv1_2 protocols
    final LayeredConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
        sslcontext,
        new String[] { "TLSv1.1", "TLSv1.2" },
        null,
        hostnameVerifier
    );

    // Setup client builder
    final HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder
        // Pardot disconnects requests after 120 seconds.
        .setConnectionTimeToLive(130, TimeUnit.SECONDS)
        .setSSLSocketFactory(sslsf);

    // Define our RequestConfigBuilder
    final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();

    // If we have a configured proxy host
    if (configuration.getProxyHost() != null) {
        // Define proxy host
        final HttpHost proxyHost = new HttpHost(
            configuration.getProxyHost(),
            configuration.getProxyPort(),
            configuration.getProxyScheme()
        );

        // If we have proxy auth enabled
        if (configuration.getProxyUsername() != null) {
            // Create credential provider
            final CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(
                new AuthScope(configuration.getProxyHost(), configuration.getProxyPort()),
                new UsernamePasswordCredentials(configuration.getProxyUsername(), configuration.getProxyPassword())
            );

            // Attach Credentials provider to client builder.
            clientBuilder.setDefaultCredentialsProvider(credsProvider);
        }

        // Attach Proxy to request config builder
        requestConfigBuilder.setProxy(proxyHost);
    }

    // Attach default request config
    clientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());

    // build http client
    httpClient = clientBuilder.build();
}