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:network.HttpClientAdaptor.java

public String doPost(String url, List<NameValuePair> parameters) {

    try {/*  w  ww.  jav  a  2 s  .c om*/

        HttpPost httpPost = new HttpPost(url);

        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout)
                .setConnectTimeout(timeout).setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).build();//?????????? 

        httpPost.setConfig(requestConfig);
        httpPost.setEntity(new UrlEncodedFormEntity(parameters));

        CloseableHttpResponse response = this.httpclient.execute(httpPost, localContext);
        BufferedReader br = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent(), this.encode));
        String htmlStr = null;
        int c = 0;
        StringBuilder temp = new StringBuilder();
        while ((c = br.read()) != -1) {
            temp.append((char) c);
        }
        htmlStr = temp.toString();

        httpPost.completed();
        httpPost.releaseConnection();

        return htmlStr;
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(HttpClientAdaptor.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(HttpClientAdaptor.class.getName()).log(Level.SEVERE, null, ex);
    }

    return null;
}

From source file:org.blocks4j.reconf.infra.http.layer.SimpleHttpClient.java

private static RequestConfig createBasicHttpParams(long timeout, TimeUnit timeUnit) {
    int timemillis = (int) TimeUnit.MILLISECONDS.convert(timeout, timeUnit);
    return RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES).setConnectTimeout(timemillis)
            .setSocketTimeout(timemillis).setConnectionRequestTimeout(timemillis).build();
}

From source file:HCNIOEngine.java

private CloseableHttpAsyncClient createCloseableHttpAsyncClient() throws Exception {
    HttpAsyncClientBuilder builder = HttpAsyncClientBuilder.create();
    builder.useSystemProperties();//from  ww  w .j  a v a2 s . c o m
    builder.setSSLContext(SSLContext.getDefault());
    builder.setConnectionReuseStrategy(DefaultConnectionReuseStrategy.INSTANCE);
    builder.setMaxConnPerRoute(2);
    builder.setMaxConnTotal(2);
    builder.setDefaultRequestConfig(RequestConfig.custom().setConnectionRequestTimeout(1000)
            .setConnectTimeout(2000).setSocketTimeout(2000).build());
    //        builder.setHttpProcessor()
    CloseableHttpAsyncClient hc = builder.build();
    hc.start();
    return hc;
}

From source file:org.springframework.cloud.netflix.ribbon.apache.RibbonLoadBalancingHttpClient.java

@Override
public RibbonApacheHttpResponse execute(RibbonApacheHttpRequest request, final IClientConfig configOverride)
        throws Exception {
    final RequestConfig.Builder builder = RequestConfig.custom();
    IClientConfig config = configOverride != null ? configOverride : this.config;
    builder.setConnectTimeout(config.get(CommonClientConfigKey.ConnectTimeout, this.connectTimeout));
    builder.setSocketTimeout(config.get(CommonClientConfigKey.ReadTimeout, this.readTimeout));
    builder.setRedirectsEnabled(config.get(CommonClientConfigKey.FollowRedirects, this.followRedirects));

    final RequestConfig requestConfig = builder.build();

    if (isSecure(configOverride)) {
        final URI secureUri = UriComponentsBuilder.fromUri(request.getUri()).scheme("https").build().toUri();
        request = request.withNewUri(secureUri);
    }/*from   w ww  .  ja va  2s. c  o m*/

    final HttpUriRequest httpUriRequest = request.toRequest(requestConfig);
    final HttpResponse httpResponse = this.delegate.execute(httpUriRequest);
    return new RibbonApacheHttpResponse(httpResponse, httpUriRequest.getURI());
}

From source file:org.roda.core.common.notifications.HTTPNotificationProcessor.java

private boolean post(String endpoint, String content, int timeout) {
    boolean success = true;
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout)
            .setConnectionRequestTimeout(timeout).build();

    try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
        HttpPost httppost = new HttpPost(endpoint);
        httppost.setConfig(requestConfig);
        httppost.setEntity(new StringEntity(content));

        HttpResponse response = httpclient.execute(httppost);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            success = false;/*  www.jav  a2s.c  o  m*/
        } else {
            HttpEntity entity = response.getEntity();
            String responseTxt = processEntity(entity);
            LOGGER.debug("HTTP response: {}", responseTxt);
        }
    } catch (IOException e) {
        LOGGER.debug("HTTP POST error: {}", e.getMessage());
        success = false;
    }

    return success;
}

From source file:com.github.vanroy.cloud.dashboard.config.CloudDashboardConfig.java

@Bean
public HttpClient HttpClient() {
    return HttpClients.custom().setMaxConnTotal(100)
            .setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(2000).build())
            .setDefaultRequestConfig(RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(1000)
                    .setConnectionRequestTimeout(1000).build())
            .build();/*from   w  w  w  .j a v a  2  s  .com*/
}

From source file:org.incode.module.commchannel.dom.api.GeocodingService.java

@Programmatic
public GeocodedAddress lookup(final String address) {

    if (demo) {/*from w ww .  j a  va  2s  . c o m*/
        return demoResponse();
    }

    final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout * 1000)
            .setConnectTimeout(timeout * 1000).build();

    final CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig)
            .useSystemProperties().build();

    try {
        final String uri = buildUri(address);
        final HttpGet httpGet = new HttpGet(uri);
        final CloseableHttpResponse response = httpClient.execute(httpGet);

        try {
            HttpEntity entity = response.getEntity();
            final String json = EntityUtils.toString(entity, "UTF-8");

            return asGeocodedAddress(json);
        } finally {
            response.close();
        }
    } catch (Exception ex) {
        return null;
    }
}

From source file:org.wso2.appcloud.integration.test.utils.clients.LogsClient.java

public String[] getSnapshotLogs(String applicationKey, String applicationRevision)
        throws AppCloudIntegrationTestException {
    HttpClient httpclient = null;//from w  w w  . j a  va  2s.c  o  m
    org.apache.http.HttpResponse response = null;
    try {
        httpclient = HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();
        int timeout = (int) AppCloudIntegrationTestUtils.getTimeOutPeriod();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout)
                .setConnectTimeout(timeout).build();
        HttpPost httppost = new HttpPost(this.endpoint);
        httppost.setConfig(requestConfig);
        List<NameValuePair> params = new ArrayList<NameValuePair>(3);
        params.add(new BasicNameValuePair(PARAM_NAME_ACTION, "getSnapshotLogs"));
        params.add(new BasicNameValuePair(PARAM_NAME_APPLICATION_HASH_ID, applicationKey));
        params.add(new BasicNameValuePair(PARAM_NAME_APPLICATION_REVISION, applicationRevision));
        httppost.setEntity(new UrlEncodedFormEntity(params, UTF_8_ENCODING));
        httppost.setHeader(HEADER_COOKIE, getRequestHeaders().get(HEADER_COOKIE));
        response = httpclient.execute(httppost);
        String[] resultArray = new String[2];
        resultArray[0] = String.valueOf(response.getStatusLine().getStatusCode());
        resultArray[1] = EntityUtils.toString(response.getEntity());
        return resultArray;
    } catch (IOException e) {
        log.error("Failed to invoke app icon update API.", e);
        throw new AppCloudIntegrationTestException("Failed to invoke app icon update API.", e);
    } finally {
        HttpClientUtils.closeQuietly(response);
        HttpClientUtils.closeQuietly(httpclient);
    }

}

From source file:org.daybreak.coccinella.webmagic.ImageDownloader.java

@Override
public Page download(Request request, Task task) {
    Site site = null;//www  .j a  v  a  2 s.c  o  m
    if (task != null) {
        site = task.getSite();
    }
    Set<Integer> acceptStatCode;
    String charset = null;
    Map<String, String> headers = null;
    if (site != null) {
        acceptStatCode = site.getAcceptStatCode();
        charset = site.getCharset();
        headers = site.getHeaders();
    } else {
        acceptStatCode = Sets.newHashSet(200);
    }
    logger.info("downloading image " + request.getUrl());
    RequestBuilder requestBuilder;
    if (request instanceof CrawlerRequest) {
        CrawlerRequest crawlerRequest = (CrawlerRequest) request;
        try {
            requestBuilder = RequestBuilder.post().setUri(crawlerRequest.getUrl())
                    .setEntity(crawlerRequest.createEntity());
        } catch (UnsupportedEncodingException ex) {
            logger.warn("The encoding is not supported: " + crawlerRequest.getCrawler().getEncode());
            return null;
        }
    } else {
        requestBuilder = RequestBuilder.get().setUri(request.getUrl());
    }
    if (headers != null) {
        for (Map.Entry<String, String> headerEntry : headers.entrySet()) {
            requestBuilder.addHeader(headerEntry.getKey(), headerEntry.getValue());
        }
    }
    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom()
            .setConnectionRequestTimeout(site.getTimeOut()).setSocketTimeout(site.getTimeOut())
            .setConnectTimeout(site.getTimeOut()).setCookieSpec(CookieSpecs.BEST_MATCH);
    if (site != null && site.getHttpProxy() != null) {
        requestConfigBuilder.setProxy(site.getHttpProxy());
    }
    requestBuilder.setConfig(requestConfigBuilder.build());
    CloseableHttpResponse httpResponse = null;
    try {
        httpResponse = getHttpClient(site).execute(requestBuilder.build());
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (acceptStatCode.contains(statusCode)) {
            ImagePage imagePage = new ImagePage(ImageIO.read(httpResponse.getEntity().getContent()));
            imagePage.setRawText("");
            imagePage.setUrl(new PlainText(request.getUrl()));
            imagePage.setRequest(request);
            imagePage.setStatusCode(httpResponse.getStatusLine().getStatusCode());
            return imagePage;
        } else {
            logger.warn("code error " + statusCode + "\t" + request.getUrl());
            return null;
        }
    } catch (IOException e) {
        logger.warn("download image " + request.getUrl() + " error", e);
        if (site.getCycleRetryTimes() > 0) {
            return addToCycleRetry(request, site);
        }
        return null;
    } finally {
        try {
            if (httpResponse != null) {
                //ensure the connection is released back to pool
                EntityUtils.consume(httpResponse.getEntity());
            }
        } catch (IOException e) {
            logger.warn("close response fail", e);
        }
    }
}