Java Code Examples for org.apache.http.client.config.RequestConfig#custom()

The following examples show how to use org.apache.http.client.config.RequestConfig#custom() . 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: HttpClientFactory.java    From aliyun-tsdb-java-sdk with Apache License 2.0 6 votes vote down vote up
private static RequestConfig initRequestConfig(Config config) {
    RequestConfig requestConfig = null;

    // 设置请求
    int httpConnectTimeout = config.getHttpConnectTimeout();
    // 需要设置
    if (httpConnectTimeout >= 0) {
        RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
        // ConnectTimeout:连接超时.连接建立时间,三次握手完成时间.
        requestConfigBuilder.setConnectTimeout(httpConnectTimeout * 1000);
        // SocketTimeout:Socket请求超时.数据传输过程中数据包之间间隔的最大时间.
        requestConfigBuilder.setSocketTimeout(httpConnectTimeout * 1000);
        // ConnectionRequestTimeout:httpclient使用连接池来管理连接,这个时间就是从连接池获取连接的超时时间,可以想象下数据库连接池
        requestConfigBuilder.setConnectionRequestTimeout(httpConnectTimeout * 1000);
        requestConfig = requestConfigBuilder.build();
    }

    return requestConfig;
}
 
Example 2
Source File: ApacheUtils.java    From ibm-cos-sdk-java with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a new HttpClientContext used for request execution.
 */
public static HttpClientContext newClientContext(HttpClientSettings settings,
                                                 Map<String, ? extends Object>
                                                         attributes) {
    final HttpClientContext clientContext = new HttpClientContext();

    if (attributes != null && !attributes.isEmpty()) {
        for (Map.Entry<String, ?> entry : attributes.entrySet()) {
            clientContext.setAttribute(entry.getKey(), entry.getValue());
        }
    }

    addPreemptiveAuthenticationProxy(clientContext, settings);

    RequestConfig.Builder builder = RequestConfig.custom();
    disableNormalizeUri(builder);

    clientContext.setRequestConfig(builder.build());
    clientContext.setAttribute(HttpContextUtils.DISABLE_SOCKET_PROXY_PROPERTY, settings.disableSocketProxy());
    return clientContext;

}
 
Example 3
Source File: HttpClientAdapter.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
private synchronized void initImpl() {
    if (impl == null) {
        HttpClientBuilder builder = createBuilder();

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

        for (HttpClientAdapterListener listener : nativeListeners) {
            listener.onBuild(builder);
        }
        impl = builder.build();
    }
}
 
Example 4
Source File: HttpClientManager.java    From pentaho-kettle with Apache License 2.0 6 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 );
  }
  httpClientBuilder.setDefaultRequestConfig( requestConfigBuilder.build() );

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

  return httpClientBuilder.build();
}
 
Example 5
Source File: HttpClientAdapter.java    From katharsis-framework with Apache License 2.0 6 votes vote down vote up
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 6
Source File: HttpGetter.java    From commafeed with Apache License 2.0 6 votes vote down vote up
public static CloseableHttpClient newClient(int timeout) {
	HttpClientBuilder builder = HttpClients.custom();
	builder.useSystemProperties();
	builder.addInterceptorFirst(REMOVE_INCORRECT_CONTENT_ENCODING);
	builder.disableAutomaticRetries();

	builder.setSSLContext(SSL_CONTEXT);
	builder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE);

	RequestConfig.Builder configBuilder = RequestConfig.custom();
	configBuilder.setCookieSpec(CookieSpecs.IGNORE_COOKIES);
	configBuilder.setSocketTimeout(timeout);
	configBuilder.setConnectTimeout(timeout);
	configBuilder.setConnectionRequestTimeout(timeout);
	builder.setDefaultRequestConfig(configBuilder.build());

	builder.setDefaultConnectionConfig(ConnectionConfig.custom().setCharset(Consts.ISO_8859_1).build());

	return builder.build();
}
 
Example 7
Source File: UrkundAPIUtil.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
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 8
Source File: HttpClientUtil.java    From redis-manager with Apache License 2.0 5 votes vote down vote up
/**
 * 设置代理及其他配置
 *
 * @return
 */
private static RequestConfig getRequestConfig(HttpHost httpHost) {
    int TIMEOUT = 1000 * 60 * 5;
    RequestConfig.Builder custom = RequestConfig.custom();
    if (httpHost != null) {
        custom.setProxy(httpHost);
    }
    return custom.setConnectTimeout(TIMEOUT)
            .setSocketTimeout(TIMEOUT)
            .setConnectionRequestTimeout(TIMEOUT)
            .build();
}
 
Example 9
Source File: HttpsClientProvider.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Create configuration for requests with default timeouts set to 10s.
 */
private RequestConfig buildCustomRequestConfig() {
    final RequestConfig.Builder builder = RequestConfig.custom();
    builder.setConnectionRequestTimeout(10 * 1000);
    builder.setSocketTimeout(10 * 1000);
    builder.setConnectTimeout(10 * 1000);
    return builder.build();
}
 
Example 10
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 11
Source File: NexusClientFactory.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Nullable
public T createClient(final URL repositoryUrl,
                      final String username,
                      final String password)
{
  checkNotNull(repositoryUrl);
  checkNotNull(username);
  checkNotNull(password);

  AuthScope scope = new AuthScope(repositoryUrl.getHost(), -1);
  CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  credentialsProvider.setCredentials(scope, new UsernamePasswordCredentials(username, password));

  RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
  requestConfigBuilder.setExpectContinueEnabled(true);

  AuthCache authCache = new BasicAuthCache();
  authCache.put(new HttpHost(repositoryUrl.getHost(), repositoryUrl.getPort()), new BasicScheme());

  HttpClientContext httpClientContext = HttpClientContext.create();
  httpClientContext.setAuthCache(authCache);
  httpClientContext.setRequestConfig(requestConfigBuilder.build());

  try {
    return createClient(
        HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build(),
        httpClientContext,
        repositoryUrl.toURI()
    );
  }
  catch (URISyntaxException e) {
    log.warn("Uri exception creating Client", e);
  }

  return null;
}
 
Example 12
Source File: HttpRequestUtil.java    From Alice-LiveMan with GNU Affero General Public License v3.0 5 votes vote down vote up
public static String downloadUrl(URI url, String cookies, Map<String, String> requestProperties, Charset charset) throws IOException {
    HttpGet httpGet = new HttpGet(url);
    HttpClientContext context = HttpClientContext.create();
    RequestConfig.Builder builder = RequestConfig.custom();
    builder.setConnectTimeout(2000).setConnectionRequestTimeout(2000).setSocketTimeout(5000).setCookieSpec(CookieSpecs.IGNORE_COOKIES).setRedirectsEnabled(true);
    httpGet.setConfig(builder.build());
    if (StringUtils.isNotBlank(cookies)) {
        httpGet.setHeader("Cookie", cookies);
    }
    httpGet.setHeader("Accept", "*/*");
    httpGet.setHeader("Accept-Encoding", "gzip, deflate");
    httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36");
    if (requestProperties != null) {
        for (Map.Entry<String, String> entry : requestProperties.entrySet()) {
            httpGet.setHeader(entry.getKey(), entry.getValue());
        }
    }
    try (CloseableHttpResponse httpResponse = client.execute(httpGet, context)) {
        HttpEntity responseEntity = httpResponse.getEntity();
        if (httpResponse.getStatusLine().getStatusCode() != 200) {
            throw new IOException(httpResponse.getStatusLine().getStatusCode() + " " + httpResponse.getStatusLine().getReasonPhrase() + "\n Headers:" + Arrays.toString(httpResponse.getAllHeaders()) + "\n" + EntityUtils.toString(responseEntity));
        }
        return EntityUtils.toString(responseEntity, charset);
    } catch (IllegalStateException e) {
        initClient();
        throw e;
    }
}
 
Example 13
Source File: ApacheUtils.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new HttpClientContext used for request execution.
 */
public static HttpClientContext newClientContext(ProxyConfiguration proxyConfiguration) {
    HttpClientContext clientContext = new HttpClientContext();
    addPreemptiveAuthenticationProxy(clientContext, proxyConfiguration);

    RequestConfig.Builder builder = RequestConfig.custom();
    disableNormalizeUri(builder);

    clientContext.setRequestConfig(builder.build());
    return clientContext;

}
 
Example 14
Source File: HttpComponentsHttpInvokerRequestExecutor.java    From java-technology-stack with MIT License 4 votes vote down vote up
private RequestConfig.Builder cloneRequestConfig() {
	return (this.requestConfig != null ? RequestConfig.copy(this.requestConfig) : RequestConfig.custom());
}
 
Example 15
Source File: HttpConnection.java    From arangodb-java-driver with Apache License 2.0 4 votes vote down vote up
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();
}
 
Example 16
Source File: UrkundAPIUtil.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
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 17
Source File: RestAgentConnector.java    From vicinity-gateway-api with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 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 18
Source File: HttpRequestSteps.java    From vividus with Apache License 2.0 3 votes vote down vote up
/**
 * Set up custom request configurations
 * @param configItems Table representing list of configuration items with columns "name" and "value"
 *  specifying their names and values respectively.
 * Available configs:
 * <ul>
 * <li>expectContinueEnabled (boolean, default:{@code false})
 *  - determines whether the 'Expect: 100-Continue' handshake is enabled</li>
 * <li>staleConnectionCheckEnabled (boolean, default:{@code false})
 *  - determines whether stale connection check is to be used</li>
 * <li>redirectsEnabled (boolean, default:{@code true})
 *  - determines whether redirects should be handled automatically</li>
 * <li>relativeRedirectsAllowed (boolean, default:{@code true})
 *  - determines whether relative redirects should be rejected</li>
 * <li>circularRedirectsAllowed (boolean, default:{@code false})
 *  - determines whether circular redirects (redirects to the same location) should be allowed</li>
 * <li>authenticationEnabled (boolean, default:{@code true})
 *  - determines whether authentication should be handled automatically</li>
 * <li>contentCompressionEnabled (boolean, default:{@code true})
 *  - determines whether the target server is requested to compress content</li>
 * <li>normalizeUri (boolean, default:{@code true})
 *  - determines whether client should normalize URIs in requests or not</li>
 * <li>maxRedirects (int, default:{@code 50}) - returns the maximum number of redirects to be followed</li>
 * <li>connectionRequestTimeout (int, default:{@code -1})
 *  - returns the timeout in milliseconds used when requesting a connection from the connection manager</li>
 * <li>connectTimeout (int, default:{@code -1})
 *  - determines the timeout in milliseconds until a connection is established</li>
 * <li>socketTimeout (int, default:{@code -1})
 *  - defines the socket timeout ({@code SO_TIMEOUT}) in milliseconds,
 * which is the timeout for waiting for data or, put differently,
 * a maximum period inactivity between two consecutive data packets</li>
 * <li>cookieSpec (String, default:{@code null})
 *  - determines the name of the cookie specification to be used for HTTP state management</li>
 * </ul>
 * @throws ReflectiveOperationException if any unknown parameter is set in configuration items
 */
@When("I set HTTP request configuration:$configItems")
public void setCustomRequestConfig(ExamplesTable configItems) throws ReflectiveOperationException
{
    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
    for (Entry<String, String> entry : configItems.getRow(0).entrySet())
    {
        Field field = requestConfigBuilder.getClass().getDeclaredField(entry.getKey());
        field.setAccessible(true);
        field.set(requestConfigBuilder, castType(field.getType().getName(), entry.getValue()));
    }
    httpTestContext.putRequestConfig(requestConfigBuilder.build());
}
 
Example 19
Source File: HttpComponentsClientHttpRequestFactory.java    From spring4-understanding with Apache License 2.0 2 votes vote down vote up
/**
 * Return a builder for modifying the factory-level {@link RequestConfig}.
 * @since 4.2
 */
private RequestConfig.Builder requestConfigBuilder() {
	return (this.requestConfig != null ? RequestConfig.copy(this.requestConfig) : RequestConfig.custom());
}
 
Example 20
Source File: HttpComponentsClientHttpRequestFactory.java    From spring-analysis-note with MIT License 2 votes vote down vote up
/**
 * Return a builder for modifying the factory-level {@link RequestConfig}.
 * @since 4.2
 */
private RequestConfig.Builder requestConfigBuilder() {
	return (this.requestConfig != null ? RequestConfig.copy(this.requestConfig) : RequestConfig.custom());
}