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.tinymediamanager.scraper.util.StreamingUrl.java

/**
 * get the InputStream of the content. Be aware: using this class needs you to close the connection per hand calling the method closeConnection()
 * /*from   w  ww  .j  av  a2  s  . co m*/
 * @return the InputStream of the content
 */
@Override
public InputStream getInputStream() throws IOException {
    // workaround for local files
    if (url.startsWith("file:")) {
        String newUrl = url.replace("file:", "");
        File file = new File(newUrl);
        return new FileInputStream(file);
    }

    BasicHttpContext localContext = new BasicHttpContext();

    // replace our API keys for logging...
    String logUrl = url.replaceAll("api_key=\\w+", "api_key=<API_KEY>").replaceAll("api/\\d+\\w+",
            "api/<API_KEY>");
    LOGGER.debug("getting " + logUrl);
    HttpGet httpget = new HttpGet(url);
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000)
            .build();
    httpget.setConfig(requestConfig);

    // set custom headers
    for (Header header : headersRequest) {
        httpget.addHeader(header);
    }

    try {
        response = client.execute(httpget, localContext);
        headersResponse = response.getAllHeaders();
        entity = response.getEntity();
        responseStatus = response.getStatusLine();
        if (entity != null) {
            return entity.getContent();
        }

    } catch (UnknownHostException e) {
        LOGGER.error("proxy or host not found/reachable", e);
    } catch (Exception e) {
        LOGGER.error("Exception getting url " + logUrl, e);
    }
    return new ByteArrayInputStream("".getBytes());
}

From source file:org.zalando.stups.tokens.CloseableHttpProvider.java

public CloseableHttpProvider(ClientCredentials clientCredentials, UserCredentials userCredentials,
        URI accessTokenUri, HttpConfig httpConfig) {
    this.userCredentials = userCredentials;
    this.accessTokenUri = accessTokenUri;
    requestConfig = RequestConfig.custom().setSocketTimeout(httpConfig.getSocketTimeout())
            .setConnectTimeout(httpConfig.getConnectTimeout())
            .setConnectionRequestTimeout(httpConfig.getConnectionRequestTimeout())
            .setStaleConnectionCheckEnabled(httpConfig.isStaleConnectionCheckEnabled()).build();

    // prepare basic auth credentials
    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(accessTokenUri.getHost(), accessTokenUri.getPort()),
            new UsernamePasswordCredentials(clientCredentials.getId(), clientCredentials.getSecret()));

    client = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();

    host = new HttpHost(accessTokenUri.getHost(), accessTokenUri.getPort(), accessTokenUri.getScheme());

    // enable basic auth for the request
    final AuthCache authCache = new BasicAuthCache();
    final BasicScheme basicAuth = new BasicScheme();
    authCache.put(host, basicAuth);//from www .  j  a  v a  2s.c  om

    localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);
}

From source file:com.ibm.nytimes.NewYorkTimes.java

public BestSellerList getList() throws Exception {
    BestSellerList returnedList = new BestSellerList();

    try {/*from   w ww .ja v  a2 s  .c  o m*/
        if (listName != null && listDate != null && url != null && apiKey != null) {
            RequestConfig config = RequestConfig.custom().setSocketTimeout(10 * 1000)
                    .setConnectTimeout(10 * 1000).build();
            CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(config).build();

            URIBuilder builder = new URIBuilder();
            builder.setScheme("http").setHost(url).setPath("/svc/books/v2/lists/" + listDate + "/" + listName)
                    .setParameter("api-key", apiKey);
            URI uri = builder.build();
            HttpGet httpGet = new HttpGet(uri);
            httpGet.setHeader("Content-Type", "text/plain");

            HttpResponse httpResponse = httpclient.execute(httpGet);

            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                BufferedReader rd = new BufferedReader(
                        new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));

                // Read all the books from the best seller list
                ObjectMapper mapper = new ObjectMapper();
                returnedList = mapper.readValue(rd, BestSellerList.class);
            } else {
                logger.error("could not get list from ny times http code {}",
                        httpResponse.getStatusLine().getStatusCode());
            }
        }
    } catch (Exception e) {
        logger.error("could not get list from ny times {}", e.getMessage());
        throw e;
    }

    return returnedList;
}

From source file:com.feedeo.web.client.AbstractWebClient.java

protected HttpClient createHttpClient() {

    final SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(true).setTcpNoDelay(true).build();

    final ConnectionConfig connectionConfig = ConnectionConfig.custom().build();

    final RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(30000)
            .setConnectTimeout(30000).setSocketTimeout(30000).setStaleConnectionCheckEnabled(false).build();

    final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setMaxTotal(256);//from  w w  w . j  a va 2  s  . c om
    connectionManager.setDefaultMaxPerRoute(256);

    IdleConnectionMonitorThread staleMonitor = new IdleConnectionMonitorThread(connectionManager);
    staleMonitor.start();

    try {
        staleMonitor.join(1000);
    } catch (InterruptedException ignored) {
    }

    final ConnectionKeepAliveStrategy connectionKeepAliveStrategy = new ConnectionKeepAliveStrategy() {
        @Override
        public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
            HeaderElementIterator iterator = new BasicHeaderElementIterator(
                    response.headerIterator(CONN_KEEP_ALIVE));
            while (iterator.hasNext()) {
                HeaderElement header = iterator.nextElement();
                String param = header.getName();
                String value = header.getValue();
                if (value != null && param.equalsIgnoreCase("timeout")) {
                    return Long.parseLong(value) * 1000;
                }
            }
            return 5 * 1000;
        }
    };

    return HttpClientBuilder.create().setConnectionManager(connectionManager)
            .setDefaultRequestConfig(requestConfig).setDefaultSocketConfig(socketConfig)
            .setDefaultConnectionConfig(connectionConfig).setKeepAliveStrategy(connectionKeepAliveStrategy)
            .build();
}

From source file:network.thunder.client.communications.HTTPS.java

public boolean connectPOST(String URL) {
    try {/*  w w  w.j  a  v  a 2  s .  com*/

        RequestConfig.custom().setConnectTimeout(10 * 1000).build();
        httpClient = HttpClients.createDefault();
        httpPost = new HttpPost(URL);
        nvps = new ArrayList<NameValuePair>();
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

From source file:org.apache.sling.etcd.testing.EtcdHandlerTest.java

@Before
public void setUp() {
    connectionManager = new PoolingHttpClientConnectionManager();
    final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000)
            .setRedirectsEnabled(true).setStaleConnectionCheckEnabled(true).build();
    httpClient = HttpClients.custom().setConnectionManager(connectionManager)
            .setDefaultRequestConfig(requestConfig).build();
}

From source file:com.linecorp.platform.channel.sample.ApiHttpClient.java

public ApiHttpClient(final String channelAccessToken) {

    RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeoutInMillis)
            .setConnectTimeout(timeoutInMillis).build();

    CloseableHttpAsyncClient asyncClient = HttpAsyncClientBuilder.create()
            .setDefaultRequestConfig(requestConfig)
            .addInterceptorLast((HttpRequest httpRequest, HttpContext httpContext) -> {
                httpRequest.addHeader("X-Line-ChannelToken", channelAccessToken);
                httpRequest.addHeader("Content-Type", "application/json; charser=UTF-8");
                httpRequest.removeHeaders("Accept");
                httpRequest.addHeader("Accept", "application/json; charset=UTF-8");
            }).setMaxConnTotal(maxConnections).setMaxConnPerRoute(maxConnections).disableCookieManagement()
            .build();/*from   w ww .j a  v a  2s  . co m*/

    asyncRestTemplate = new AsyncRestTemplate(new HttpComponentsAsyncClientHttpRequestFactory(asyncClient));
    asyncRestTemplate.setErrorHandler(new ApiResponseErrorHandler());

    httpHeaders = new HttpHeaders();
    httpHeaders.set("X-Line-ChannelToken", channelAccessToken);
    httpHeaders.setContentType(new MediaType("application", "json", Charset.forName("UTF-8")));
    List<MediaType> list = new ArrayList<>();
    list.add(new MediaType("application", "json", Charset.forName("UTF-8")));
    httpHeaders.setAccept(list);

    objectMapper = new ObjectMapper();
    objectMapper.configure(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME, true);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
    objectMapper.setAnnotationIntrospector(new JaxbAnnotationIntrospector(TypeFactory.defaultInstance()));
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}

From source file:com.intuit.wasabi.export.rest.impl.DefaultRestDriver.java

private HttpClientBuilder createHttpClientBuilder(final Driver.Configuration configuration) {
    PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager();

    poolingHttpClientConnectionManager.setMaxTotal(200);
    poolingHttpClientConnectionManager.setDefaultMaxPerRoute(50);

    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(configuration.getConnectionTimeout())
            .setSocketTimeout(configuration.getSocketTimeout()).build();

    return HttpClients.custom().setConnectionManager(poolingHttpClientConnectionManager)
            .setDefaultRequestConfig(requestConfig);
}

From source file:co.tuzza.clicksend4j.http.HttpClientUtils.java

private RequestConfig buildRequestConfig() {
    Builder builder = RequestConfig.custom();

    builder.setSocketTimeout(socketTimeout);
    builder.setConnectTimeout(connectionTimeout);
    builder.setAuthenticationEnabled(true);

    return builder.build();
}

From source file: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)
            .setStaleConnectionCheckEnabled(false).setConnectTimeout(timemillis).setSocketTimeout(timemillis)
            .setConnectionRequestTimeout(timemillis).build();
}