Search in sources :

Example 41 with RequestConfig

use of org.apache.http.client.config.RequestConfig in project cas by apereo.

the class SimpleHttpClientFactoryBean method buildHttpClient.

/**
 * Build a HTTP client based on the current properties.
 *
 * @return the built HTTP client
 */
@SneakyThrows
private CloseableHttpClient buildHttpClient() {
    final ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
    final LayeredConnectionSocketFactory sslsf = this.sslSocketFactory;
    final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", plainsf).register("https", sslsf).build();
    final PoolingHttpClientConnectionManager connMgmr = new PoolingHttpClientConnectionManager(registry);
    connMgmr.setMaxTotal(this.maxPooledConnections);
    connMgmr.setDefaultMaxPerRoute(this.maxConnectionsPerRoute);
    connMgmr.setValidateAfterInactivity(DEFAULT_TIMEOUT);
    final HttpHost httpHost = new HttpHost(InetAddress.getLocalHost());
    final HttpRoute httpRoute = new HttpRoute(httpHost);
    connMgmr.setMaxPerRoute(httpRoute, MAX_CONNECTIONS_PER_ROUTE);
    final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(this.readTimeout).setConnectTimeout((int) this.connectionTimeout).setConnectionRequestTimeout((int) this.connectionTimeout).setCircularRedirectsAllowed(this.circularRedirectsAllowed).setRedirectsEnabled(this.redirectsEnabled).setAuthenticationEnabled(this.authenticationEnabled).build();
    final HttpClientBuilder builder = HttpClients.custom().setConnectionManager(connMgmr).setDefaultRequestConfig(requestConfig).setSSLSocketFactory(sslsf).setSSLHostnameVerifier(this.hostnameVerifier).setRedirectStrategy(this.redirectionStrategy).setDefaultCredentialsProvider(this.credentialsProvider).setDefaultCookieStore(this.cookieStore).setConnectionReuseStrategy(this.connectionReuseStrategy).setConnectionBackoffStrategy(this.connectionBackoffStrategy).setServiceUnavailableRetryStrategy(this.serviceUnavailableRetryStrategy).setProxyAuthenticationStrategy(this.proxyAuthenticationStrategy).setDefaultHeaders(this.defaultHeaders).useSystemProperties();
    return builder.build();
}
Also used : HttpRoute(org.apache.http.conn.routing.HttpRoute) RequestConfig(org.apache.http.client.config.RequestConfig) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) LayeredConnectionSocketFactory(org.apache.http.conn.socket.LayeredConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) LayeredConnectionSocketFactory(org.apache.http.conn.socket.LayeredConnectionSocketFactory) HttpHost(org.apache.http.HttpHost) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) SneakyThrows(lombok.SneakyThrows)

Example 42 with RequestConfig

use of org.apache.http.client.config.RequestConfig in project scheduling by ow2-proactive.

the class ProActiveVersionUtility method getProActiveServerVersion.

protected static String getProActiveServerVersion(ApplicationContext currentContext) {
    int timeout = (int) TimeUnit.SECONDS.toMillis(2);
    RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();
    try (CloseableHttpClient httpClient = new HttpClientBuilder().setDefaultRequestConfig(config).useSystemProperties().build()) {
        HttpGet getMethod = new HttpGet(currentContext.getResourceUrl("version"));
        HttpResponse response = httpClient.execute(getMethod);
        String jsonObject = handleResponse(response);
        if (jsonObject != null)
            return jsonObject;
    } catch (IOException ignore) {
    // ignore exception, default value will be used
    }
    return VERSION_UNDEFINED;
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) HttpClientBuilder(org.ow2.proactive.http.HttpClientBuilder) IOException(java.io.IOException) CommonEntryPoint(org.ow2.proactive_grid_cloud_portal.cli.CommonEntryPoint)

Example 43 with RequestConfig

use of org.apache.http.client.config.RequestConfig in project camel by apache.

the class HttpPollingConsumer method doReceive.

protected Exchange doReceive(int timeout) {
    Exchange exchange = endpoint.createExchange();
    HttpRequestBase method = createMethod(exchange);
    HttpClientContext httpClientContext = new HttpClientContext();
    // set optional timeout in millis
    if (timeout > 0) {
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).build();
        httpClientContext.setRequestConfig(requestConfig);
    }
    HttpEntity responeEntity = null;
    try {
        // execute request
        HttpResponse response = httpClient.execute(method, httpClientContext);
        int responseCode = response.getStatusLine().getStatusCode();
        responeEntity = response.getEntity();
        Object body = HttpHelper.readResponseBodyFromInputStream(responeEntity.getContent(), exchange);
        // lets store the result in the output message.
        Message message = exchange.getOut();
        message.setBody(body);
        // lets set the headers
        Header[] headers = response.getAllHeaders();
        HeaderFilterStrategy strategy = endpoint.getHeaderFilterStrategy();
        for (Header header : headers) {
            String name = header.getName();
            // mapping the content-type
            if (name.toLowerCase().equals("content-type")) {
                name = Exchange.CONTENT_TYPE;
            }
            String value = header.getValue();
            if (strategy != null && !strategy.applyFilterToExternalHeaders(name, value, exchange)) {
                message.setHeader(name, value);
            }
        }
        message.setHeader(Exchange.HTTP_RESPONSE_CODE, responseCode);
        if (response.getStatusLine() != null) {
            message.setHeader(Exchange.HTTP_RESPONSE_TEXT, response.getStatusLine().getReasonPhrase());
        }
        return exchange;
    } catch (IOException e) {
        throw new RuntimeCamelException(e);
    } finally {
        if (responeEntity != null) {
            try {
                EntityUtils.consume(responeEntity);
            } catch (IOException e) {
            // nothing what we can do
            }
        }
    }
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) HttpEntity(org.apache.http.HttpEntity) Message(org.apache.camel.Message) HttpResponse(org.apache.http.HttpResponse) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) HeaderFilterStrategy(org.apache.camel.spi.HeaderFilterStrategy) IOException(java.io.IOException) Exchange(org.apache.camel.Exchange) Header(org.apache.http.Header) RuntimeCamelException(org.apache.camel.RuntimeCamelException)

Example 44 with RequestConfig

use of org.apache.http.client.config.RequestConfig in project dubbo by alibaba.

the class RestProtocol method doRefer.

protected <T> T doRefer(Class<T> serviceType, URL url) throws RpcException {
    if (connectionMonitor == null) {
        connectionMonitor = new ConnectionMonitor();
    }
    // TODO more configs to add
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    // 20 is the default maxTotal of current PoolingClientConnectionManager
    connectionManager.setMaxTotal(url.getParameter(Constants.CONNECTIONS_KEY, 20));
    connectionManager.setDefaultMaxPerRoute(url.getParameter(Constants.CONNECTIONS_KEY, 20));
    connectionMonitor.addConnectionManager(connectionManager);
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)).setSocketTimeout(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)).build();
    SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(true).setTcpNoDelay(true).build();
    CloseableHttpClient httpClient = HttpClientBuilder.create().setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {

        public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
            HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
            while (it.hasNext()) {
                HeaderElement he = it.nextElement();
                String param = he.getName();
                String value = he.getValue();
                if (value != null && param.equalsIgnoreCase("timeout")) {
                    return Long.parseLong(value) * 1000;
                }
            }
            // TODO constant
            return 30 * 1000;
        }
    }).setDefaultRequestConfig(requestConfig).setDefaultSocketConfig(socketConfig).build();
    ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient);
    ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
    clients.add(client);
    client.register(RpcContextFilter.class);
    for (String clazz : Constants.COMMA_SPLIT_PATTERN.split(url.getParameter(Constants.EXTENSION_KEY, ""))) {
        if (!StringUtils.isEmpty(clazz)) {
            try {
                client.register(Thread.currentThread().getContextClassLoader().loadClass(clazz.trim()));
            } catch (ClassNotFoundException e) {
                throw new RpcException("Error loading JAX-RS extension class: " + clazz.trim(), e);
            }
        }
    }
    // TODO protocol
    ResteasyWebTarget target = client.target("http://" + url.getHost() + ":" + url.getPort() + "/" + getContextPath(url));
    return target.proxy(serviceType);
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) ResteasyClientBuilder(org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder) ResteasyClient(org.jboss.resteasy.client.jaxrs.ResteasyClient) SocketConfig(org.apache.http.config.SocketConfig) ConnectionKeepAliveStrategy(org.apache.http.conn.ConnectionKeepAliveStrategy) HeaderElement(org.apache.http.HeaderElement) ApacheHttpClient4Engine(org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine) HttpContext(org.apache.http.protocol.HttpContext) HttpResponse(org.apache.http.HttpResponse) BasicHeaderElementIterator(org.apache.http.message.BasicHeaderElementIterator) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) BasicHeaderElementIterator(org.apache.http.message.BasicHeaderElementIterator) HeaderElementIterator(org.apache.http.HeaderElementIterator) RpcException(com.alibaba.dubbo.rpc.RpcException) ResteasyWebTarget(org.jboss.resteasy.client.jaxrs.ResteasyWebTarget)

Example 45 with RequestConfig

use of org.apache.http.client.config.RequestConfig in project jersey by jersey.

the class DisableContentEncodingTest method testDisabledByRequestConfig.

@Test
public void testDisabledByRequestConfig() {
    ClientConfig cc = new ClientConfig(GZipEncoder.class);
    final RequestConfig requestConfig = RequestConfig.custom().setContentCompressionEnabled(false).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("", enc);
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) WebTarget(javax.ws.rs.client.WebTarget) ClientConfig(org.glassfish.jersey.client.ClientConfig) Client(javax.ws.rs.client.Client) Test(org.junit.Test) JerseyTest(org.glassfish.jersey.test.JerseyTest)

Aggregations

RequestConfig (org.apache.http.client.config.RequestConfig)91 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)33 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)31 HttpGet (org.apache.http.client.methods.HttpGet)29 HttpPost (org.apache.http.client.methods.HttpPost)19 Test (org.junit.Test)16 IOException (java.io.IOException)14 StringEntity (org.apache.http.entity.StringEntity)14 WxErrorException (me.chanjar.weixin.common.exception.WxErrorException)13 HttpResponse (org.apache.http.HttpResponse)12 WxError (me.chanjar.weixin.common.bean.result.WxError)11 HttpEntity (org.apache.http.HttpEntity)11 URI (java.net.URI)10 PoolingHttpClientConnectionManager (org.apache.http.impl.conn.PoolingHttpClientConnectionManager)10 InputStream (java.io.InputStream)9 HttpHost (org.apache.http.HttpHost)9 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)9 Configurable (org.apache.http.client.methods.Configurable)7 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)7 Header (org.apache.http.Header)6