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.opendaylight.infrautils.diagstatus.shell.HttpClient.java

public HttpResponse sendRequest(HttpRequest request) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    if (httpclient == null) {
        throw new ClientProtocolException("Couldn't create an HTTP client");
    }//from  ww w  . j  a  v a 2s  . co m
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(request.getTimeout())
            .setConnectTimeout(request.getTimeout()).build();
    HttpRequestBase httprequest;
    String method = request.getMethod();
    if (method.equalsIgnoreCase("GET")) {
        httprequest = new HttpGet(request.getUri());
    } else if (method.equalsIgnoreCase("POST")) {
        httprequest = new HttpPost(request.getUri());
        if (request.getEntity() != null) {
            StringEntity sentEntity = new StringEntity(request.getEntity());
            sentEntity.setContentType(request.getContentType());
            ((HttpEntityEnclosingRequestBase) httprequest).setEntity(sentEntity);
        }
    } else if (method.equalsIgnoreCase("PUT")) {
        httprequest = new HttpPut(request.getUri());
        if (request.getEntity() != null) {
            StringEntity sentEntity = new StringEntity(request.getEntity());
            sentEntity.setContentType(request.getContentType());
            ((HttpEntityEnclosingRequestBase) httprequest).setEntity(sentEntity);
        }
    } else if (method.equalsIgnoreCase("DELETE")) {
        httprequest = new HttpDelete(request.getUri());
    } else {
        httpclient.close();
        throw new IllegalArgumentException(
                "This profile class only supports GET, POST, PUT, and DELETE methods");
    }
    httprequest.setConfig(requestConfig);
    // add request headers
    Iterator<String> headerIterator = request.getHeaders().keySet().iterator();
    while (headerIterator.hasNext()) {
        String header = headerIterator.next();
        Iterator<String> valueIterator = request.getHeaders().get(header).iterator();
        while (valueIterator.hasNext()) {
            httprequest.addHeader(header, valueIterator.next());
        }
    }
    CloseableHttpResponse response = httpclient.execute(httprequest);
    try {
        int httpResponseCode = response.getStatusLine().getStatusCode();
        HashMap<String, List<String>> headerMap = new HashMap<>();
        // copy response headers
        HeaderIterator it = response.headerIterator();
        while (it.hasNext()) {
            Header nextHeader = it.nextHeader();
            String name = nextHeader.getName();
            String value = nextHeader.getValue();
            if (headerMap.containsKey(name)) {
                headerMap.get(name).add(value);
            } else {
                List<String> list = new ArrayList<>();
                list.add(value);
                headerMap.put(name, list);
            }
        }
        if (httpResponseCode > 299) {
            return new HttpResponse(httpResponseCode, response.getStatusLine().getReasonPhrase(), headerMap);
        }
        Optional<HttpEntity> receivedEntity = Optional.ofNullable(response.getEntity());
        String httpBody = receivedEntity.isPresent() ? EntityUtils.toString(receivedEntity.get()) : null;
        return new HttpResponse(response.getStatusLine().getStatusCode(), httpBody, headerMap);
    } finally {
        response.close();
    }
}

From source file:com.turn.ttorrent.client.tracker.HTTPTrackerClient.java

@Override
public void start() throws Exception {
    super.start();
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build();
    httpclient = HttpAsyncClients.custom().setDefaultRequestConfig(requestConfig).build();
    httpclient.start();/*  w ww. j  ava2s  .  c o  m*/
}

From source file:org.apache.manifoldcf.jettyrunner.ManifoldCFJettyShutdown.java

public void shutdownJetty() throws Exception {
    // Pick up shutdown token
    String shutdownToken = System.getProperty("org.apache.manifoldcf.jettyshutdowntoken");
    if (shutdownToken != null) {
        int socketTimeout = 900000;
        int connectionTimeout = 300000;

        HttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();

        RequestConfig.Builder requestBuilder = RequestConfig.custom().setCircularRedirectsAllowed(true)
                .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(false)
                .setExpectContinueEnabled(true).setConnectTimeout(connectionTimeout)
                .setConnectionRequestTimeout(socketTimeout);

        HttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).setMaxConnTotal(1)
                .disableAutomaticRetries().setDefaultRequestConfig(requestBuilder.build())
                .setDefaultSocketConfig(
                        SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build())
                .setRequestExecutor(new HttpRequestExecutor(socketTimeout))
                .setRedirectStrategy(new DefaultRedirectStrategy()).build();

        HttpPost method = new HttpPost(
                jettyBaseURL + "/shutdown?token=" + URLEncoder.encode(shutdownToken, "UTF-8"));
        method.setEntity(new StringEntity("", ContentType.create("text/plain", StandardCharsets.UTF_8)));
        try {//from  w  ww  . j a  v  a 2 s  .  c o m
            HttpResponse httpResponse = httpClient.execute(method);
            int resultCode = httpResponse.getStatusLine().getStatusCode();
            if (resultCode != 200)
                throw new Exception("Received result code " + resultCode + " from POST");
        } catch (org.apache.http.NoHttpResponseException e) {
            // This is ok and expected
        }
    } else {
        throw new Exception("No jetty shutdown token specified");
    }
}

From source file:com.terracotta.nrplugin.rest.nr.MetricReporter.java

@PostConstruct
private void init() {
    RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(10000).setSocketTimeout(10000)
            .setConnectionRequestTimeout(5000).setStaleConnectionCheckEnabled(true).build();
    HttpClientBuilder httpClientBuilder = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig);
    if (useProxy) {
        int parsedProxyPort = 8080;
        try {// www  .  j  a  v a  2s  .c o  m
            parsedProxyPort = Integer.parseInt(proxyPort);
        } catch (NumberFormatException e) {
            log.warn("Could not parse the proxyPort. Defaulting to 8080.");
            parsedProxyPort = 8080;
        }

        HttpHost proxy = new HttpHost(proxyHostname, parsedProxyPort, proxyScheme);
        httpClientBuilder.setProxy(proxy);
        log.info("Configuring HttpClient with proxy '" + proxy.toString() + "'");
    }
    httpClient = httpClientBuilder.build();
}

From source file:ca.uhn.fhir.rest.client.apache.ApacheRestfulClientFactory.java

public synchronized HttpClient getNativeHttpClient() {
    if (myHttpClient == null) {

        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000,
                TimeUnit.MILLISECONDS);
        connectionManager.setMaxTotal(getPoolMaxTotal());
        connectionManager.setDefaultMaxPerRoute(getPoolMaxPerRoute());

        // @formatter:off
        RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(getSocketTimeout())
                .setConnectTimeout(getConnectTimeout())
                .setConnectionRequestTimeout(getConnectionRequestTimeout()).setStaleConnectionCheckEnabled(true)
                .setProxy(myProxy).build();

        HttpClientBuilder builder = HttpClients.custom().setConnectionManager(connectionManager)
                .setDefaultRequestConfig(defaultRequestConfig).disableCookieManagement();

        if (myProxy != null && StringUtils.isNotBlank(getProxyUsername())
                && StringUtils.isNotBlank(getProxyPassword())) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(myProxy.getHostName(), myProxy.getPort()),
                    new UsernamePasswordCredentials(getProxyUsername(), getProxyPassword()));
            builder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
            builder.setDefaultCredentialsProvider(credsProvider);
        }/*from w  w  w  . ja  v a 2 s.com*/

        myHttpClient = builder.build();
        // @formatter:on

    }

    return myHttpClient;
}

From source file:org.phenotips.pingback.internal.client.data.IPPingDataProvider.java

@Override
public Map<String, Object> provideData() {
    Map<String, Object> jsonMap = new HashMap<>();

    CloseableHttpResponse response = null;
    try {//from w  ww  .ja v  a  2  s  .  c  o m
        String uri = configuration.getProperty(IP_FETCH_URL_PROPERTY);
        HttpGet method = new HttpGet(uri);
        RequestConfig config = RequestConfig.custom().setSocketTimeout(2000).build();
        method.setConfig(config);
        response = this.client.execute(method);
        JSONObject obj = new JSONObject(IOUtils.toString(response.getEntity().getContent()));

        if (obj.has(PROPERTY_IP)) {
            jsonMap.put(PROPERTY_IP, obj.get(PROPERTY_IP));
        }
    } catch (Exception e) {
        logWarning("Making IP request failed.", e);
    } finally {
        if (response != null) {
            try {
                EntityUtils.consumeQuietly(response.getEntity());
                response.close();
            } catch (IOException ex) {
                // Not dangerous
            }
        }
    }

    return jsonMap;
}

From source file:edgeserver.HTTPClient.java

String GetPageContent(String url, List<NameValuePair> postParams) throws Exception {
    int CONNECTION_TIMEOUT = 30 * 1000; // timeout in millis
    RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(CONNECTION_TIMEOUT)
            .setConnectTimeout(CONNECTION_TIMEOUT).setSocketTimeout(CONNECTION_TIMEOUT).build();

    HttpPost request = new HttpPost(url);
    request.setConfig(requestConfig);// w w w. j  a v  a 2s.  c  o m

    request.setHeader("User-Agent", USER_AGENT);
    request.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    request.setHeader("Accept-Language", "en-US,en;q=0.5");

    if (postParams != null)
        request.setEntity(new UrlEncodedFormEntity(postParams));

    HttpResponse response = client.execute(request);
    int responseCode = response.getStatusLine().getStatusCode();

    //System.out.println("\nSending 'GET' request to URL : " + url);
    //System.out.println("Response Code : " + responseCode);

    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null) {
        result.append(line);
    }

    // set cookies
    setCookies(response.getFirstHeader("Set-Cookie") == null ? ""
            : response.getFirstHeader("Set-Cookie").toString());

    return result.toString();

}

From source file:com.wallellen.wechat.mp.util.http.MaterialVoiceAndImageDownloadRequestExecutor.java

public InputStream execute(CloseableHttpClient httpClient, HttpHost httpProxy, String uri, String materialId)
        throws WxErrorException, IOException {
    HttpPost httpPost = new HttpPost(uri);
    if (httpProxy != null) {
        RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build();
        httpPost.setConfig(config);/*  ww w .ja  va2s  .  c o  m*/
    }

    Map<String, String> params = new HashMap<>();
    params.put("media_id", materialId);
    httpPost.setEntity(new StringEntity(WxGsonBuilder.create().toJson(params)));
    CloseableHttpResponse response = httpClient.execute(httpPost);
    // 
    InputStream inputStream = InputStreamResponseHandler.INSTANCE.handleResponse(response);
    byte[] responseContent = IOUtils.toByteArray(inputStream);
    String responseContentString = new String(responseContent, "UTF-8");
    if (responseContentString.length() < 100) {
        try {
            WxError wxError = WxGsonBuilder.create().fromJson(responseContentString, WxError.class);
            if (wxError.getErrorCode() != 0) {
                throw new WxErrorException(wxError);
            }
        } catch (com.google.gson.JsonSyntaxException ex) {
            return new ByteArrayInputStream(responseContent);
        }
    }
    return new ByteArrayInputStream(responseContent);
}

From source file:org.springframework.remoting.httpinvoker.HttpComponentsHttpInvokerRequestExecutorTests.java

@Test
public void defaultSettingsOfHttpClientMergedOnExecutorCustomization() throws IOException {
    RequestConfig defaultConfig = RequestConfig.custom().setConnectTimeout(1234).build();
    CloseableHttpClient client = mock(CloseableHttpClient.class,
            withSettings().extraInterfaces(Configurable.class));
    Configurable configurable = (Configurable) client;
    when(configurable.getConfig()).thenReturn(defaultConfig);

    HttpComponentsHttpInvokerRequestExecutor executor = new HttpComponentsHttpInvokerRequestExecutor(client);
    HttpInvokerClientConfiguration config = mockHttpInvokerClientConfiguration("http://fake-service");
    HttpPost httpPost = executor.createHttpPost(config);
    assertSame("Default client configuration is expected", defaultConfig, httpPost.getConfig());

    executor.setConnectionRequestTimeout(4567);
    HttpPost httpPost2 = executor.createHttpPost(config);
    assertNotNull(httpPost2.getConfig());
    assertEquals(4567, httpPost2.getConfig().getConnectionRequestTimeout());
    // Default connection timeout merged
    assertEquals(1234, httpPost2.getConfig().getConnectTimeout());
}