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:com.mirth.connect.plugins.httpauth.oauth2.OAuth2Authenticator.java

@Override
public AuthenticationResult authenticate(RequestInfo request) throws Exception {
    OAuth2HttpAuthProperties properties = getReplacedProperties(request);

    CloseableHttpClient client = null;//from   w  w w  .jav a 2 s . co m
    CloseableHttpResponse response = null;

    try {
        // Create and configure the client and context 
        RegistryBuilder<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                .<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory());
        ConnectorPluginProperties pluginProperties = null;
        if (CollectionUtils.isNotEmpty(properties.getConnectorPluginProperties())) {
            pluginProperties = properties.getConnectorPluginProperties().iterator().next();
        }
        provider.getHttpConfiguration().configureSocketFactoryRegistry(pluginProperties, socketFactoryRegistry);
        BasicHttpClientConnectionManager httpClientConnectionManager = new BasicHttpClientConnectionManager(
                socketFactoryRegistry.build());
        httpClientConnectionManager.setSocketConfig(SocketConfig.custom().setSoTimeout(SOCKET_TIMEOUT).build());
        HttpClientBuilder clientBuilder = HttpClients.custom()
                .setConnectionManager(httpClientConnectionManager);
        HttpUtil.configureClientBuilder(clientBuilder);
        client = clientBuilder.build();

        HttpClientContext context = HttpClientContext.create();
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(SOCKET_TIMEOUT)
                .setSocketTimeout(SOCKET_TIMEOUT).setStaleConnectionCheckEnabled(true).build();
        context.setRequestConfig(requestConfig);

        URIBuilder uriBuilder = new URIBuilder(properties.getVerificationURL());

        // Add query parameters
        if (properties.getTokenLocation() == TokenLocation.QUERY) {
            List<String> paramList = request.getQueryParameters().get(properties.getLocationKey());
            if (CollectionUtils.isNotEmpty(paramList)) {
                for (String value : paramList) {
                    uriBuilder.addParameter(properties.getLocationKey(), value);
                }
            }
        }

        // Build the final URI and create a GET request
        HttpGet httpGet = new HttpGet(uriBuilder.build());

        // Add headers
        if (properties.getTokenLocation() == TokenLocation.HEADER) {
            List<String> headerList = request.getHeaders().get(properties.getLocationKey());
            if (CollectionUtils.isNotEmpty(headerList)) {
                for (String value : headerList) {
                    httpGet.addHeader(properties.getLocationKey(), value);
                }
            }
        }

        // Execute the request
        response = client.execute(httpGet, context);

        // Determine authentication from the status code 
        if (response.getStatusLine().getStatusCode() < 400) {
            return AuthenticationResult.Success();
        } else {
            return AuthenticationResult.Failure();
        }
    } finally {
        HttpClientUtils.closeQuietly(response);
        HttpClientUtils.closeQuietly(client);
    }
}

From source file:com.wareninja.opensource.discourse.utils.MyWebClient.java

protected void initBase() {
    SSLContext sslContext = SSLContexts.createSystemDefault();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
            SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER);

    httpRequestConfig = RequestConfig.custom().setSocketTimeout(TIMEOUT).setConnectTimeout(TIMEOUT)
            .setCookieSpec(CookieSpecs.BEST_MATCH).build();

    cookieStore = new BasicCookieStore();

    httpClient = HttpClientBuilder.create().setSSLSocketFactory(sslsf).setDefaultCookieStore(cookieStore)
            .setDefaultRequestConfig(httpRequestConfig).build();

    localContext = HttpClientContext.create();

}

From source file:RGSCommonUtils.UniversalConnectionInterfaceImp.java

@Override
public String POST_Request(String p_uri, Object... p_objects) throws IOException {
    String result = "";
    HttpPost request = new HttpPost(p_uri);
    RequestConfig config;//from  w ww.  j ava  2s  .co m
    if (this.proxy != null)
        config = RequestConfig.custom().setProxy(this.proxy).build();
    else
        config = RequestConfig.custom().build();
    request.setConfig(config);

    request.setHeader("Content-Type", (String) p_objects[0]);

    if (p_objects.length > 0) {
        HttpEntity reqEntity = EntityBuilder.create().setText(((String) p_objects[1])).build();
        request.setEntity(reqEntity);
        CloseableHttpResponse responce = httpClient.execute(target, request);
        result = responceToString(responce);
    }

    return result;
}

From source file:org.nuxeo.connect.registration.RegistrationHelper.java

protected static HttpClientContext getHttpClientContext(String url, String login, String password) {
    HttpClientContext context = HttpClientContext.create();

    // Set credentials provider
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    if (login != null) {
        Credentials ba = new UsernamePasswordCredentials(login, password);
        credentialsProvider.setCredentials(AuthScope.ANY, ba);
    }/*from  w  ww .j av a  2 s .  com*/
    context.setCredentialsProvider(credentialsProvider);

    // Create AuthCache instance for preemptive authentication
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    try {
        authCache.put(URIUtils.extractHost(new URI(url)), basicAuth);
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
    context.setAuthCache(authCache);

    // Create request configuration
    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setConnectTimeout(10000);

    // Configure the http proxy if needed
    ProxyHelper.configureProxyIfNeeded(requestConfigBuilder, credentialsProvider, url);

    context.setRequestConfig(requestConfigBuilder.build());
    return context;
}

From source file:edu.vt.vbi.patric.common.DataApiHandler.java

public String solrQuery(SolrCore core, SolrQuery query) {

    String responseBody = null;/*from  w ww  .j av  a2s . c o m*/
    RequestConfig config = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout)
            .setConnectionRequestTimeout(timeout).build();
    try (CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build()) {

        HttpPost request = new HttpPost(baseUrl + core.getSolrCoreName());

        request.setHeader("Accept", "application/solr+json");
        request.setHeader("Content-Type", "application/solrquery+x-www-form-urlencoded");

        if (token != null) {
            request.setHeader("Authorization", token);
        }

        request.setEntity(new StringEntity(query.toString()));

        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        responseBody = client.execute(request, responseHandler);

    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
    }

    return responseBody;
}

From source file:com.kugou.opentsdb.OpenTsdb.java

private OpenTsdb(String hostname, int port, int connectionTimeout, int connectionRequestTimeout,
        int batchSizeLimit) {
    RequestConfig config = RequestConfig.custom().setConnectTimeout(connectionTimeout)
            .setConnectionRequestTimeout(connectionRequestTimeout).setCookieSpec(CookieSpecs.IGNORE_COOKIES)
            .build();/*w w  w.j a v  a2 s .  c o m*/

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setDefaultMaxPerRoute(MAX_CONNECTIONS_PER_ROUTE);
    cm.setMaxTotal(MAX_CONNECTIONS_TOTAL);
    client = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(config).build();
    host = new HttpHost(hostname, port);
    this.batchSizeLimit = batchSizeLimit;
    this.connectionTimeout = connectionTimeout;
    this.connectionRequestTimeout = connectionRequestTimeout;
}

From source file:org.glassfish.jersey.apache.connector.DisableContentEncodingTest.java

@Test
public void testEnabledByRequestConfig() {
    ClientConfig cc = new ClientConfig(GZipEncoder.class);
    final RequestConfig requestConfig = RequestConfig.custom().setContentCompressionEnabled(true).build();
    cc.property(ApacheClientProperties.REQUEST_CONFIG, requestConfig);
    cc.connectorProvider(new ApacheConnectorProvider());
    Client client = ClientBuilder.newClient(cc);
    WebTarget r = client.target(getBaseUri());

    String enc = r.request().get().readEntity(String.class);
    assertEquals("gzip,deflate", enc);
}

From source file:edu.xiyou.fruits.WebCrawler.net.HttpRequest.java

public HttpRequest() {
    RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(Config.TTIME_OUT)
            .setSocketTimeout(Config.TTIME_OUT).build();
    client = HttpClients.custom().setUserAgent(
            "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36")
            .setRetryHandler(new DefaultHttpRequestRetryHandler(Config.RETRY, true))
            .setRedirectStrategy(new LaxRedirectStrategy()).setDefaultRequestConfig(requestConfig)
            .setConnectionManager(connectionManager).build();
}

From source file:org.azkfw.crawler.CrawlerController.java

private boolean execCommand(final String aCommand, final Map<String, String> aParameter)
        throws ClientProtocolException, IOException {
    boolean result = false;

    String userAgent = "Azuki crawler controller 1.0";
    RequestConfig requestConfig = RequestConfig.custom().build();
    List<Header> headers = new ArrayList<Header>();
    headers.add(new BasicHeader("Accept-Charset", config.getCharset()));
    headers.add(new BasicHeader("Accept-Language", "ja, en;q=0.8"));
    headers.add(new BasicHeader("User-Agent", userAgent));

    StringBuilder parameter = new StringBuilder();
    if (null != aParameter) {
        for (String key : aParameter.keySet()) {
            if (0 == parameter.length()) {
                parameter.append("?");
            } else {
                parameter.append("&");
            }/*  w  w  w  .  jav  a  2 s  .co m*/
            parameter.append(key);
            parameter.append("=");
            parameter.append(aParameter.get(key));
        }
    }

    HttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig)
            .setDefaultHeaders(headers).build();

    String url = String.format("http://localhost:%d%s/%s%s", config.getPort(), config.getContextpath(),
            aCommand, parameter.toString());

    HttpGet httpGet = null;
    BufferedReader reader = null;
    try {
        debug(String.format("Command %s %s [%s]", aCommand, parameter.toString(), url));

        httpGet = new HttpGet(url);
        HttpResponse response = httpClient.execute(httpGet);
        int statusCode = response.getStatusLine().getStatusCode();

        StringBuilder html = new StringBuilder();
        reader = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent(), config.getCharset()));
        String line = null;
        while (null != (line = reader.readLine())) {
            html.append(line);
        }

        if (200 == statusCode) {
            result = true;
        } else {
            error("Error Code.[" + statusCode + "]");
            error(html.toString());
        }

    } finally {
        if (null != reader) {
            try {
                reader.close();
            } catch (IOException ex) {
                warn(ex);
            }
        }
        if (null != httpGet) {
            httpGet.abort();
        }
    }

    return result;
}

From source file:io.undertow.test.jsp.taglib.TagLibJspTestCase.java

@Test
public void testSimpleHttpServlet() throws IOException {
    TestHttpClient client = new TestHttpClient();
    try {/*  ww  w. j av a  2 s  . c om*/
        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/servletContext/test.jsp");
        get.setConfig(RequestConfig.custom().setConnectTimeout(5 * 60 * 1000).setSocketTimeout(5 * 60 * 1000)
                .build());
        HttpResponse result = client.execute(get);
        Assert.assertEquals(200, result.getStatusLine().getStatusCode());
        final String response = HttpClientUtils.readResponse(result);
        Assert.assertTrue(response.contains("java.lang.Runtime"));
    } finally {
        client.getConnectionManager().shutdown();
    }
}