Example usage for org.apache.http.client.config RequestConfig custom

List of usage examples for org.apache.http.client.config RequestConfig custom

Introduction

In this page you can find the example usage for org.apache.http.client.config RequestConfig custom.

Prototype

public static RequestConfig.Builder custom() 

Source Link

Usage

From source file:org.sonatype.nexus.testsuite.NexusHttpsITSupport.java

/**
 * @return Policy for handling cookies on client side
 */
protected RequestConfig requestConfig() {
    return RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();
}

From source file:org.camunda.bpm.engine.rest.standalone.AbstractEmptyBodyFilterTest.java

@Before
public void setUpHttpClientAndRuntimeData() {
    client = HttpClients.createDefault();
    reqConfig = RequestConfig.custom().setConnectTimeout(3 * 60 * 1000).setSocketTimeout(10 * 60 * 1000)
            .build();/*from  w ww.j ava 2s.c  o  m*/

    ProcessDefinition mockDefinition = MockProvider.createMockDefinition();

    runtimeServiceMock = mock(RuntimeService.class);
    when(processEngine.getRuntimeService()).thenReturn(runtimeServiceMock);

    mockInstantiationBuilder = mock(ProcessInstantiationBuilder.class);
    when(mockInstantiationBuilder.setVariables(any(Map.class))).thenReturn(mockInstantiationBuilder);
    when(mockInstantiationBuilder.businessKey(anyString())).thenReturn(mockInstantiationBuilder);
    when(mockInstantiationBuilder.caseInstanceId(anyString())).thenReturn(mockInstantiationBuilder);
    when(runtimeServiceMock.createProcessInstanceById(anyString())).thenReturn(mockInstantiationBuilder);

    ProcessInstanceWithVariables resultInstanceWithVariables = MockProvider.createMockInstanceWithVariables();
    when(mockInstantiationBuilder.executeWithVariablesInReturn(anyBoolean(), anyBoolean()))
            .thenReturn(resultInstanceWithVariables);

    ProcessDefinitionQuery processDefinitionQueryMock = mock(ProcessDefinitionQuery.class);
    when(processDefinitionQueryMock.processDefinitionKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY))
            .thenReturn(processDefinitionQueryMock);
    when(processDefinitionQueryMock.withoutTenantId()).thenReturn(processDefinitionQueryMock);
    when(processDefinitionQueryMock.latestVersion()).thenReturn(processDefinitionQueryMock);
    when(processDefinitionQueryMock.singleResult()).thenReturn(mockDefinition);

    RepositoryService repositoryServiceMock = mock(RepositoryService.class);
    when(processEngine.getRepositoryService()).thenReturn(repositoryServiceMock);
    when(repositoryServiceMock.createProcessDefinitionQuery()).thenReturn(processDefinitionQueryMock);
}

From source file:com.crawler.app.fetcher.PageFetcher.java

public PageFetcher(CrawlConfig config) {
    super(config);

    RequestConfig requestConfig = RequestConfig.custom().setExpectContinueEnabled(false)
            .setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).setRedirectsEnabled(false)
            //.setRelativeRedirectsAllowed(true)
            .setSocketTimeout(config.getSocketTimeout()).setConnectTimeout(config.getConnectionTimeout())
            .build();//w w w .  j a  va  2 s  .  c  o m

    RegistryBuilder<ConnectionSocketFactory> connRegistryBuilder = RegistryBuilder.create();
    connRegistryBuilder.register("http", PlainConnectionSocketFactory.INSTANCE);
    if (config.isIncludeHttpsPages()) {
        try { // Fixing: https://code.google.com/p/crawler4j/issues/detail?id=174
            // By always trusting the ssl certificate
            SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
                //@Override
                public boolean isTrusted(final X509Certificate[] chain, String authType) {
                    return true;
                }
            }).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                    SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            connRegistryBuilder.register("https", sslsf);
        } catch (Exception e) {
            logger.warn("Exception thrown while trying to register https");
            logger.debug("Stacktrace", e);
        }
    }

    Registry<ConnectionSocketFactory> connRegistry = connRegistryBuilder.build();
    connectionManager = new PoolingHttpClientConnectionManager(connRegistry);
    connectionManager.setMaxTotal(config.getMaxTotalConnections());
    connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsPerHost());

    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder.setDefaultRequestConfig(requestConfig);
    clientBuilder.setConnectionManager(connectionManager);
    clientBuilder.setUserAgent(config.getUserAgentString());

    if (config.getProxyHost() != null) {
        if (config.getProxyUsername() != null) {
            BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(new AuthScope(config.getProxyHost(), config.getProxyPort()),
                    new UsernamePasswordCredentials(config.getProxyUsername(), config.getProxyPassword()));
            clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        }

        HttpHost proxy = new HttpHost(config.getProxyHost(), config.getProxyPort());
        clientBuilder.setProxy(proxy);
        logger.debug("Working through Proxy: {}", proxy.getHostName());
    }

    httpClient = clientBuilder.build();
    if (config.getAuthInfos() != null && !config.getAuthInfos().isEmpty()) {
        doAuthetication(config.getAuthInfos());
    }

    if (connectionMonitorThread == null) {
        connectionMonitorThread = new IdleConnectionMonitorThread(connectionManager);
    }
    connectionMonitorThread.start();
}

From source file:de.freegroup.twogo.plotter.rpc.Client.java

private String getToken(CloseableHttpClient httpclient) throws Exception {

    RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
    HttpPost request = new HttpPost(this.serverUrl + "Echo");
    request.setConfig(config);/*from  w ww.  j  a  v a 2  s.com*/
    request.setHeader("Content-Type", "text/plain");
    request.setHeader("X-CSRF-Token", "Fetch");

    try {

        JSONObject message = buildParam("echo", new String[] { "any" });

        StringEntity body = new StringEntity(message.toString(),
                ContentType.create("application/json", Consts.UTF_8));

        request.setEntity(body);
        System.out.println(">> Request URI: " + request.getRequestLine().getUri());

        CloseableHttpResponse response = httpclient.execute(request);

        JSONTokener tokener = new JSONTokener(new BasicResponseHandler().handleResponse(response));
        Object rawResponseMessage = tokener.nextValue();
        JSONObject responseMessage = (JSONObject) rawResponseMessage;
        if (responseMessage == null) {
            throw new ClientError("Invalid response type - " + rawResponseMessage.getClass());
        }

        return (responseMessage.getJSONObject("result").getJSONObject("header").getString("value"));

    } catch (Exception e) {
        throw new ClientError(e);
    }
}

From source file:com.beginner.core.utils.HttpUtil.java

/**
 * <p>To request the GET way.</p>
 * //from  ww  w.  j a  v a 2s .  c  om
 * @param url      request URI
 * @param timeout   request timeout time in milliseconds(The default timeout time for 30 seconds.)
 * @return String   response result
 * @throws Exception
 * @since 1.0.0
 */
public static String get(String url, Integer timeout) throws Exception {

    // Validates input
    if (StringUtils.isBlank(url))
        throw new IllegalArgumentException("The url cannot be null and cannot be empty.");

    //The default timeout time for 30 seconds
    if (null == timeout)
        timeout = 30000;

    CloseableHttpClient httpClient = HttpClients.createDefault();

    CloseableHttpResponse httpResponse = null;
    String result = null;

    try {
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout)
                .setConnectTimeout(timeout).build();

        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(requestConfig);

        httpResponse = httpClient.execute(httpGet);

        HttpEntity entity = httpResponse.getEntity();
        result = EntityUtils.toString(entity);

        EntityUtils.consume(entity);
    } catch (Exception e) {
        logger.error("GET?", e);
        return null;
    } finally {
        if (null != httpResponse)
            httpResponse.close();
        if (null != httpClient)
            httpClient.close();
    }
    return result;
}

From source file:com.google.devtools.build.lib.remote.blobstore.RestBlobStore.java

/**
 * Creates a new instance./*  ww  w . j  a  va  2s  . co m*/
 *
 * @param baseUrl base URL for the remote cache
 * @param poolSize maximum number of simultaneous connections
 */
public RestBlobStore(String baseUrl, int poolSize, int timeoutMillis) throws IOException {
    validateUrl(baseUrl);
    this.baseUrl = baseUrl;
    connMan = new PoolingHttpClientConnectionManager();
    connMan.setDefaultMaxPerRoute(poolSize);
    connMan.setMaxTotal(poolSize);
    clientFactory = HttpClientBuilder.create();
    clientFactory.setConnectionManager(connMan);
    clientFactory.setConnectionManagerShared(true);
    clientFactory.setDefaultRequestConfig(RequestConfig.custom()
            // Timeout to establish a connection.
            .setConnectTimeout(timeoutMillis)
            // Timeout between reading data.
            .setSocketTimeout(timeoutMillis).build());
}

From source file:securitytools.common.http.HttpClientFactory.java

public static CloseableHttpAsyncClient buildAsync(ClientConfiguration clientConfiguration)
        throws NoSuchAlgorithmException {
    HttpAsyncClientBuilder builder = HttpAsyncClients.custom();

    // Certificate Validation
    // TODO//  w  ww . jav a 2 s.co m
    if (clientConfiguration.isCertificateValidationEnabled()) {
        builder.setSSLStrategy(new SSLIOSessionStrategy(SSLContext.getDefault(),
                SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER));
    } else {
        // Disable
        SSLIOSessionStrategy sslStrategy = new SSLIOSessionStrategy(SSLContext.getDefault(),
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        builder.setSSLStrategy(sslStrategy);
    }

    // Timeouts
    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
    requestConfigBuilder.setConnectTimeout(clientConfiguration.getConnectionTimeout());
    requestConfigBuilder.setConnectionRequestTimeout(clientConfiguration.getConnectionTimeout());
    requestConfigBuilder.setSocketTimeout(clientConfiguration.getSocketTimeout());
    builder.setDefaultRequestConfig(requestConfigBuilder.build());

    // User Agent
    builder.setUserAgent(clientConfiguration.getUserAgent());

    // Proxy
    if (clientConfiguration.getProxyHost() != null) {
        builder.setProxy(clientConfiguration.getProxyHost());
    }

    return builder.build();
}

From source file:se.svt.helios.serviceregistration.consul.ConsulClient.java

public ConsulClient(String baseUri) {
    this(baseUri,
            HttpAsyncClients.custom()/*  w  w w .  java 2  s .c  om*/
                    .setDefaultRequestConfig(RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT)
                            .setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT)
                            .setSocketTimeout(SOCKET_TIMEOUT).build())
                    .build());
}

From source file:org.frontcache.client.FrontCacheClient.java

private FrontCacheClient(String frontcacheURL) {
    final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(CONNECTION_TIMEOUT)
            .setConnectTimeout(CONNECTION_TIMEOUT).setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();

    ConnectionKeepAliveStrategy keepAliveStrategy = new ConnectionKeepAliveStrategy() {
        @Override//w w w  . j  ava  2s . c om
        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")) {
                    return Long.parseLong(value) * 1000;
                }
            }
            return 10 * 1000;
        }
    };

    client = HttpClients.custom().setDefaultRequestConfig(requestConfig)
            .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false))
            .setKeepAliveStrategy(keepAliveStrategy).setRedirectStrategy(new RedirectStrategy() {
                @Override
                public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context)
                        throws ProtocolException {
                    return false;
                }

                @Override
                public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response,
                        HttpContext context) throws ProtocolException {
                    return null;
                }
            }).build();

    this.frontCacheURL = frontcacheURL;

    if (frontcacheURL.endsWith("/"))
        this.frontCacheURI = frontcacheURL + IO_URI;
    else
        this.frontCacheURI = frontcacheURL + "/" + IO_URI;
}