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.springframework.cloud.netflix.ribbon.apache.RibbonApacheHttpRequestTests.java

@Test
public void testNullEntity() throws Exception {
    String uri = "http://example.com";
    LinkedMultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
    headers.add("my-header", "my-value");
    headers.add(HttpEncoding.CONTENT_LENGTH, "5192");
    LinkedMultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("myparam", "myparamval");
    RibbonApacheHttpRequest httpRequest = new RibbonApacheHttpRequest(new RibbonCommandContext("example", "GET",
            uri, false, headers, params, null, new ArrayList<RibbonRequestCustomizer>()));

    HttpUriRequest request = httpRequest.toRequest(RequestConfig.custom().build());

    assertThat("request is wrong type", request, is(not(instanceOf(HttpEntityEnclosingRequest.class))));
    assertThat("uri is wrong", request.getURI().toString(), startsWith(uri));
    assertThat("my-header is missing", request.getFirstHeader("my-header"), is(notNullValue()));
    assertThat("my-header is wrong", request.getFirstHeader("my-header").getValue(), is(equalTo("my-value")));
    assertThat("Content-Length is wrong", request.getFirstHeader(HttpEncoding.CONTENT_LENGTH).getValue(),
            is(equalTo("5192")));
    assertThat("myparam is missing", request.getURI().getQuery(), is(equalTo("myparam=myparamval")));

}

From source file:org.apache.solr.client.solrj.impl.ExternalHttpClientTest.java

/**
 * The internal client created by HttpSolrClient is a SystemDefaultHttpClient
 * which takes care of merging request level params (such as timeout) with the
 * configured defaults./*  w ww.  j a v  a  2 s .  c om*/
 *
 * However, if an external HttpClient is passed to HttpSolrClient,
 * the logic in InternalHttpClient.executeMethod replaces the configured defaults
 * by request level params if they exist. That is why we must test a setting such
 * as timeout with an external client to assert that the defaults are indeed being
 * used
 *
 * See SOLR-6245 for more details
 */
@Test
public void testTimeoutWithExternalClient() throws Exception {

    HttpClientBuilder builder = HttpClientBuilder.create();
    RequestConfig config = RequestConfig.custom().setSocketTimeout(2000).build();
    builder.setDefaultRequestConfig(config);

    try (CloseableHttpClient httpClient = builder.build();
            HttpSolrClient solrClient = new HttpSolrClient(jetty.getBaseUrl().toString() + "/slow/foo",
                    httpClient)) {

        SolrQuery q = new SolrQuery("*:*");
        try {
            solrClient.query(q, SolrRequest.METHOD.GET);
            fail("No exception thrown.");
        } catch (SolrServerException e) {
            assertTrue(e.getMessage().contains("Timeout"));
        }
    }
}

From source file:org.dspace.app.sherpa.SHERPAService.java

public SHERPAResponse searchByJournalISSN(String query) {
    String endpoint = ConfigurationManager.getProperty("sherpa.romeo.url");
    String apiKey = ConfigurationManager.getProperty("sherpa.romeo.apikey");

    HttpGet method = null;/*w  w  w . j  av a2s .  co  m*/
    SHERPAResponse sherpaResponse = null;
    int numberOfTries = 0;

    while (numberOfTries < maxNumberOfTries && sherpaResponse == null) {
        numberOfTries++;

        if (log.isDebugEnabled()) {
            log.debug(String.format(
                    "Trying to contact SHERPA/RoMEO - attempt %d of %d; timeout is %d; sleep between timeouts is %d",
                    numberOfTries, maxNumberOfTries, timeout, sleepBetweenTimeouts));
        }

        try {
            Thread.sleep(sleepBetweenTimeouts);

            URIBuilder uriBuilder = new URIBuilder(endpoint);
            uriBuilder.addParameter("issn", query);
            uriBuilder.addParameter("versions", "all");
            if (StringUtils.isNotBlank(apiKey))
                uriBuilder.addParameter("ak", apiKey);

            method = new HttpGet(uriBuilder.build());
            method.setConfig(RequestConfig.custom().setConnectionRequestTimeout(timeout)
                    .setConnectTimeout(timeout).setSocketTimeout(timeout).build());
            // Execute the method.

            HttpResponse response = client.execute(method);
            int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode != HttpStatus.SC_OK) {
                sherpaResponse = new SHERPAResponse("SHERPA/RoMEO return not OK status: " + statusCode);
            }

            HttpEntity responseBody = response.getEntity();

            if (null != responseBody)
                sherpaResponse = new SHERPAResponse(responseBody.getContent());
            else
                sherpaResponse = new SHERPAResponse("SHERPA/RoMEO returned no response");
        } catch (Exception e) {
            log.warn("Encountered exception while contacting SHERPA/RoMEO: " + e.getMessage(), e);
        } finally {
            if (method != null) {
                method.releaseConnection();
            }
        }
    }

    if (sherpaResponse == null) {
        sherpaResponse = new SHERPAResponse("Error processing the SHERPA/RoMEO answer");
    }

    return sherpaResponse;
}

From source file:org.apache.aurora.scheduler.events.WebhookModule.java

@Override
protected void configure() {
    if (enableWebhook) {
        WebhookInfo webhookInfo = parseWebhookConfig(readWebhookFile());
        int timeout = webhookInfo.getConnectonTimeoutMsec();
        RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout) // establish connection with server eg time to TCP handshake.
                .setConnectionRequestTimeout(timeout) // get a connection from internal pool.
                .setSocketTimeout(timeout) // wait for data after connection was established.
                .build();/*from  w  w  w.j a va  2  s  .c  o  m*/
        ConnectionKeepAliveStrategy connectionStrategy = new DefaultConnectionKeepAliveStrategy();
        CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config)
                // being explicit about using default Keep-Alive strategy.
                .setKeepAliveStrategy(connectionStrategy).build();

        bind(WebhookInfo.class).toInstance(webhookInfo);
        bind(CloseableHttpClient.class).toInstance(client);
        PubsubEventModule.bindSubscriber(binder(), Webhook.class);
        bind(Webhook.class).in(Singleton.class);
    }
}

From source file:ch.ledcom.jpreseed.cli.JPreseed.java

private static JPreseed initialize() {
    CacheConfig cacheConfig = CacheConfig.custom().setMaxCacheEntries(MAX_CACHE_ENTRIES)
            .setMaxObjectSize(MAX_OBJECT_SIZE).build();
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT)
            .setSocketTimeout(SOCKET_TIMEOUT).build();

    DownloaderFactory downloaderFactory = new DownloaderFactory(CachingHttpClients.custom()
            .setCacheConfig(cacheConfig).setDefaultRequestConfig(requestConfig).build());
    return new JPreseed(downloaderFactory, new UsbCreator());
}

From source file:nya.miku.wishmaster.http.client.ExtendedHttpClient.java

/**
 *    ? ?    ?  ??//  w  w w  . j a v  a 2  s  . c o m
 * @param timeout  
 */
public static RequestConfig.Builder getDefaultRequestConfigBuilder(int timeout) {
    return RequestConfig.custom().setConnectTimeout(timeout).setConnectionRequestTimeout(timeout)
            .setSocketTimeout(timeout).setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY)
            .setStaleConnectionCheckEnabled(false);
}

From source file:org.eclipse.wst.json.core.internal.download.HttpClientProvider.java

private static File download(File file, URL url) {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    CloseableHttpResponse response = null;
    OutputStream out = null;/*from   w w w. jav a 2 s.c  om*/
    file.getParentFile().mkdirs();
    try {
        HttpHost target = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
        Builder builder = RequestConfig.custom();
        HttpHost proxy = getProxy(target);
        if (proxy != null) {
            builder = builder.setProxy(proxy);
        }
        RequestConfig config = builder.build();
        HttpGet request = new HttpGet(url.toURI());
        request.setConfig(config);
        response = httpclient.execute(target, request);
        InputStream in = response.getEntity().getContent();
        out = new BufferedOutputStream(new FileOutputStream(file));
        copy(in, out);
        return file;
    } catch (Exception e) {
        logWarning(e);
        ;
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
            }
        }
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
            }
        }
        try {
            httpclient.close();
        } catch (IOException e) {
        }
    }
    return null;
}

From source file:edu.mit.scratch.ScratchUserManager.java

public void clearMessages() throws ScratchUserException {
    try {/*from w w  w  . ja v a2s .com*/
        final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();

        final CookieStore cookieStore = new BasicCookieStore();
        final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en");
        lang.setDomain(".scratch.mit.edu");
        lang.setPath("/");
        cookieStore.addCookie(lang);

        final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
                .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build();
        final HttpUriRequest update = RequestBuilder.get()
                .setUri("https://scratch.mit.edu/messages/ajax/messages-clear/")
                .addHeader("Accept",
                        "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
                .addHeader("Referer", "https://scratch.mit.edu").addHeader("Origin", "https://scratch.mit.edu")
                .addHeader("Accept-Encoding", "gzip, deflate, sdch")
                .addHeader("Accept-Language", "en-US,en;q=0.8").addHeader("Content-Type", "application/json")
                .addHeader("X-Requested-With", "XMLHttpRequest")
                .addHeader("Cookie",
                        "scratchsessionsid=" + this.session.getSessionID() + "; scratchcsrftoken="
                                + this.session.getCSRFToken())
                .addHeader("X-CSRFToken", this.session.getCSRFToken()).build();

        httpClient.execute(update);
    } catch (final Exception e) {
        throw new ScratchUserException();
    }
}

From source file:org.openscore.content.httpclient.build.RequestConfigBuilder.java

public RequestConfig buildRequestConfig() {
    HttpHost proxy = null;// ww w. j ava 2 s  .c o  m
    if (proxyHost != null && !proxyHost.isEmpty()) {
        try {
            proxy = new HttpHost(proxyHost, Integer.parseInt(proxyPort));
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException(
                    "Cound not parse '" + HttpClientInputs.PROXY_PORT + "' input: " + e.getMessage(), e);
        }
    }
    int connectionTimeout = Integer.parseInt(this.connectionTimeout);
    int socketTimeout = Integer.parseInt(this.socketTimeout);
    //todo should we also allow user to enable redirects prohibited by the HTTP specification (on POST and PUT)? See 'LaxRedirectStrategy'
    return RequestConfig.custom()
            .setConnectTimeout(connectionTimeout <= 0 ? connectionTimeout : connectionTimeout * 1000)
            .setSocketTimeout(socketTimeout <= 0 ? socketTimeout : socketTimeout * 1000).setProxy(proxy)
            .setRedirectsEnabled(Boolean.parseBoolean(followRedirects)).build();
}