Example usage for org.apache.http.impl.client DefaultConnectionKeepAliveStrategy DefaultConnectionKeepAliveStrategy

List of usage examples for org.apache.http.impl.client DefaultConnectionKeepAliveStrategy DefaultConnectionKeepAliveStrategy

Introduction

In this page you can find the example usage for org.apache.http.impl.client DefaultConnectionKeepAliveStrategy DefaultConnectionKeepAliveStrategy.

Prototype

DefaultConnectionKeepAliveStrategy

Source Link

Usage

From source file:org.apache.aurora.scheduler.events.WebhookModule.java

@Override
protected void configure() {
    if (enableWebhook) {
        WebhookInfo webhookInfo = parseWebhookConfig(readWebhookFile());
        int timeout = webhookInfo.getConnectonTimeoutMsec();
        RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout) // establish connection with server eg time to TCP handshake.
                .setConnectionRequestTimeout(timeout) // get a connection from internal pool.
                .setSocketTimeout(timeout) // wait for data after connection was established.
                .build();//from w  w w .j ava  2  s.com
        ConnectionKeepAliveStrategy connectionStrategy = new DefaultConnectionKeepAliveStrategy();
        CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config)
                // being explicit about using default Keep-Alive strategy.
                .setKeepAliveStrategy(connectionStrategy).build();

        bind(WebhookInfo.class).toInstance(webhookInfo);
        bind(CloseableHttpClient.class).toInstance(client);
        PubsubEventModule.bindSubscriber(binder(), Webhook.class);
        bind(Webhook.class).in(Singleton.class);
    }
}

From source file:com.miapc.ipudong.Application.java

@Bean
public RestTemplate getRestTemplate() {
    SSLContext sslcontext = null;
    Set<KeyManager> keymanagers = new LinkedHashSet<>();
    Set<TrustManager> trustmanagers = new LinkedHashSet<>();
    try {/*from  w  w w .  ja  v a2  s .  co  m*/
        trustmanagers.add(new HttpsTrustManager());
        KeyManager[] km = keymanagers.toArray(new KeyManager[keymanagers.size()]);
        TrustManager[] tm = trustmanagers.toArray(new TrustManager[trustmanagers.size()]);
        sslcontext = SSLContexts.custom().build();
        sslcontext.init(km, tm, new SecureRandom());
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
    SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,
            SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    HttpClientBuilder httpClientBuilder = HttpClients.custom();
    httpClientBuilder.setSSLSocketFactory(factory);
    // ?3?
    httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(2, true));
    // ????Keep-Alive
    httpClientBuilder.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy());

    List<Header> headers = new ArrayList<>();
    headers.add(new BasicHeader("User-Agent",
            "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36"));
    headers.add(new BasicHeader("Accept-Encoding", "gzip,deflate"));
    headers.add(new BasicHeader("Accept-Language", "zh-CN"));
    headers.add(new BasicHeader("Connection", "Keep-Alive"));
    headers.add(new BasicHeader("Authorization", "reslibu"));
    httpClientBuilder.setDefaultHeaders(headers);
    CloseableHttpClient httpClient = httpClientBuilder.build();
    if (httpClient != null) {
        // httpClient??RequestConfig
        HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(
                httpClient);
        // 
        clientHttpRequestFactory.setConnectTimeout(60 * 1000);
        // ???SocketTimeout
        clientHttpRequestFactory.setReadTimeout(5 * 60 * 1000);
        // ????
        clientHttpRequestFactory.setConnectionRequestTimeout(5000);
        // ?truePOSTPUT????false?
        // clientHttpRequestFactory.setBufferRequestBody(false);
        // ?
        List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
        messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
        messageConverters.add(new MappingJackson2HttpMessageConverter());
        messageConverters.add(new FormHttpMessageConverter());
        messageConverters.add(new MappingJackson2XmlHttpMessageConverter());

        RestTemplate restTemplate = new RestTemplate(messageConverters);
        restTemplate.setRequestFactory(clientHttpRequestFactory);
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
        return restTemplate;
    } else {
        return null;
    }

}

From source file:co.paralleluniverse.fibers.dropwizard.FiberHttpClientBuilder.java

/**
 * Add strategies to client such as ConnectionReuseStrategy and KeepAliveStrategy Note that this
 * method mutates the client object by setting the strategies
 *
 * @param client The InstrumentedHttpClient that should be configured with strategies
 *//*from w ww  .ja  v a2  s  .co  m*/
protected void setStrategiesForClient(HttpAsyncClientBuilder client) {
    final long keepAlive = configuration.getKeepAlive().toMilliseconds();

    // don't keep alive the HTTP connection and thus don't reuse the TCP socket
    if (keepAlive == 0) {
        client.setConnectionReuseStrategy(new NoConnectionReuseStrategy());
    } else {
        client.setConnectionReuseStrategy(new DefaultConnectionReuseStrategy());
        // either keep alive based on response header Keep-Alive,
        // or if the server can keep a persistent connection (-1), then override based on client's configuration
        client.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy() {
            @Override
            public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
                final long duration = super.getKeepAliveDuration(response, context);
                return (duration == -1) ? keepAlive : duration;
            }
        });
    }
}

From source file:com.guardtime.ksi.service.client.http.apache.ApacheHttpClient.java

/**
 * Creates asynchronous Apache HTTP client.
 *
 * @param settings//from ww  w.  j a v a  2  s  .  c  o m
 *         - settings to use to create client
 * @param conf
 *         - configuration related to async connection
 * @return instance of {@link CloseableHttpAsyncClient}
 */
private CloseableHttpAsyncClient createClient(AbstractHttpClientSettings settings,
        ApacheHttpClientConfiguration conf) {
    IOReactorConfig ioReactor = IOReactorConfig.custom().setIoThreadCount(conf.getMaxThreadCount()).build();
    HttpAsyncClientBuilder httpClientBuilder = HttpAsyncClients.custom().useSystemProperties()
            // allow POST redirects
            .setRedirectStrategy(new LaxRedirectStrategy()).setMaxConnTotal(conf.getMaxTotalConnectionCount())
            .setMaxConnPerRoute(conf.getMaxRouteConnectionCount()).setDefaultIOReactorConfig(ioReactor)
            .setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy())
            .setDefaultRequestConfig(createDefaultRequestConfig(settings));
    if (settings.getProxyUrl() != null) {
        DefaultProxyRoutePlanner routePlanner = createProxyRoutePlanner(settings, httpClientBuilder);
        httpClientBuilder.setRoutePlanner(routePlanner);
    }
    CloseableHttpAsyncClient httpClient = httpClientBuilder.build();
    httpClient.start();
    return httpClient;
}

From source file:com.github.marcosalis.kraken.utils.http.DefaultHttpRequestsManager.java

/**
 * Same as {@link #initialize(ConnectionKeepAliveStrategy)} with a
 * {@link DefaultConnectionKeepAliveStrategy}.
 */// ww w  .j av  a2  s  . co m
public synchronized void initialize() {
    initialize(new DefaultConnectionKeepAliveStrategy());
}

From source file:org.ofbiz.testtools.seleniumxml.RemoteRequest.java

public void runTest() {

    ClientConnectionManager ccm = new ThreadSafeClientConnManager(defaultParameters, supportedSchemes);
    //  new SingleClientConnManager(getParams(), supportedSchemes);

    DefaultHttpClient client = new DefaultHttpClient(ccm, defaultParameters);
    client.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy());

    ////from w w w  . j av a2s  . com
    // We first try to login with the loginAs to set the session.
    // Then we call the remote service.
    //
    HttpEntity entity = null;
    ResponseHandler<String> responseHandler = null;
    try {
        BasicHttpContext localContext = new BasicHttpContext();
        // Create a local instance of cookie store
        CookieStore cookieStore = new BasicCookieStore();
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

        Header sessionHeader = null;

        if (this.loginAsUrl != null) {

            String loginAsUri = this.host + this.loginAsUrl;
            String loginAsParamString = "?" + this.loginAsUserParam + "&" + this.loginAsPasswordParam;

            HttpGet req2 = new HttpGet(loginAsUri + loginAsParamString);
            System.out.println("loginAsUrl:" + loginAsUri + loginAsParamString);

            req2.setHeader("Connection", "Keep-Alive");
            HttpResponse rsp = client.execute(req2, localContext);

            Header[] headers = rsp.getAllHeaders();
            for (int i = 0; i < headers.length; i++) {
                Header hdr = headers[i];
                String headerValue = hdr.getValue();
                if (headerValue.startsWith("JSESSIONID")) {
                    sessionHeader = hdr;
                }
                System.out.println("login: " + hdr.getName() + " : " + hdr.getValue());
            }
            List<Cookie> cookies = cookieStore.getCookies();
            System.out.println("cookies.size(): " + cookies.size());
            for (int i = 0; i < cookies.size(); i++) {
                System.out.println("Local cookie(0): " + cookies.get(i));
            }
        }
        //String paramString2 = "USERNAME=" + this.parent.getUserName()
        //                   + "&PASSWORD=" + this.parent.getPassword();
        //String thisUri2 = this.host + "/eng/control/login?" + paramString2;
        //HttpGet req2 = new HttpGet ( thisUri2 );
        //req2.setHeader("Connection","Keep-Alive");
        //HttpResponse rsp = client.execute(req2, localContext);

        //Header sessionHeader = null;
        //Header[] headers = rsp.getAllHeaders();
        //for (int i=0; i<headers.length; i++) {
        //    Header hdr = headers[i];
        //    String headerValue = hdr.getValue();
        //    if (headerValue.startsWith("JSESSIONID")) {
        //        sessionHeader = hdr;
        //    }
        //    System.out.println(headers[i]);
        //    System.out.println(hdr.getName() + " : " + hdr.getValue());
        //}

        //List<Cookie> cookies = cookieStore.getCookies();
        //System.out.println("cookies.size(): " + cookies.size());
        //for (int i = 0; i < cookies.size(); i++) {
        //    System.out.println("Local cookie(0): " + cookies.get(i));
        //}
        if (HttpHandleMode.equals(this.responseHandlerMode)) {

        } else {
            responseHandler = new JsonResponseHandler(this);
        }

        String paramString = urlEncodeArgs(this.inMap, false);

        String thisUri = null;
        if (sessionHeader != null) {
            String sessionHeaderValue = sessionHeader.getValue();
            int pos1 = sessionHeaderValue.indexOf("=");
            int pos2 = sessionHeaderValue.indexOf(";");
            String sessionId = sessionHeaderValue.substring(pos1 + 1, pos2);
            thisUri = this.host + this.requestUrl + ";jsessionid=" + sessionId + "?" + paramString;
        } else {
            thisUri = this.host + this.requestUrl + "?" + paramString;
        }
        //String sessionHeaderValue = sessionHeader.getValue();
        //int pos1 = sessionHeaderValue.indexOf("=");
        //int pos2 = sessionHeaderValue.indexOf(";");
        //String sessionId = sessionHeaderValue.substring(pos1 + 1, pos2);
        //System.out.println("sessionId: " + sessionId);
        //String thisUri = this.host + this.requestUrl + ";jsessionid=" + sessionId + "?"  + paramString;
        //String thisUri = this.host + this.requestUrl + "?"  + paramString;
        System.out.println("thisUri: " + thisUri);

        HttpGet req = new HttpGet(thisUri);
        if (sessionHeader != null) {
            req.setHeader(sessionHeader);
        }

        String responseBody = client.execute(req, responseHandler, localContext);
        /*
        entity = rsp.getEntity();
                
        System.out.println("----------------------------------------");
        System.out.println(rsp.getStatusLine());
        Header[] headers = rsp.getAllHeaders();
        for (int i=0; i<headers.length; i++) {
        System.out.println(headers[i]);
        }
        System.out.println("----------------------------------------");
                
        if (entity != null) {
        System.out.println(EntityUtils.toString(rsp.getEntity()));
        }
        */
    } catch (HttpResponseException e) {
        System.out.println(e.getMessage());
    } catch (IOException e) {
        System.out.println(e.getMessage());
    } finally {
        // If we could be sure that the stream of the entity has been
        // closed, we wouldn't need this code to release the connection.
        // However, EntityUtils.toString(...) can throw an exception.

        // if there is no entity, the connection is already released
        try {
            if (entity != null)
                entity.consumeContent(); // release connection gracefully
        } catch (IOException e) {
            System.out.println("in 'finally'  " + e.getMessage());
        }

    }
    return;
}

From source file:org.vietspider.net.client.impl.AnonymousHttpClient.java

@Override
protected ConnectionKeepAliveStrategy createConnectionKeepAliveStrategy() {
    return new DefaultConnectionKeepAliveStrategy();
}

From source file:org.dcache.srm.client.HttpClientSender.java

/**
 * Creates the HttpClient used to submit SOAP requests.
 *//*www . j a  v a  2 s.co m*/
protected CloseableHttpClient createHttpClient(PoolingHttpClientConnectionManager connectionManager) {
    return HttpClients.custom().setConnectionManager(connectionManager)
            .setUserAgent("dCache/" + VERSION.getVersion())
            .setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()).build();
}

From source file:com.senseidb.svc.impl.HttpRestSenseiServiceImpl.java

private DefaultHttpClient createHttpClient(HttpRequestRetryHandler retryHandler) {
    HttpParams params = new BasicHttpParams();
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme(_scheme, _port, PlainSocketFactory.getSocketFactory()));
    ClientConnectionManager cm = new ThreadSafeClientConnManager(registry);
    DefaultHttpClient client = new DefaultHttpClient(cm, params);
    if (retryHandler == null) {
        retryHandler = new HttpRequestRetryHandler() {
            public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
                if (executionCount >= _maxRetries) {
                    // Do not retry if over max retry count
                    return false;
                }//from w ww.  jav  a 2 s.c o m
                if (exception instanceof NoHttpResponseException) {
                    // Retry if the server dropped connection on us
                    return true;
                }
                if (exception instanceof SSLHandshakeException) {
                    // Do not retry on SSL handshake exception
                    return false;
                }
                HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
                boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
                if (idempotent) {
                    // Retry if the request is considered idempotent
                    return true;
                }
                return false;
            }
        };
    }
    client.setHttpRequestRetryHandler(retryHandler);

    client.addRequestInterceptor(new HttpRequestInterceptor() {
        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            if (!request.containsHeader("Accept-Encoding")) {
                request.addHeader("Accept-Encoding", "gzip");
            }
        }
    });

    client.addResponseInterceptor(new HttpResponseInterceptor() {
        public void process(final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
            HttpEntity entity = response.getEntity();
            Header ceheader = entity.getContentEncoding();
            if (ceheader != null) {
                HeaderElement[] codecs = ceheader.getElements();
                for (int i = 0; i < codecs.length; i++) {
                    if (codecs[i].getName().equalsIgnoreCase("gzip")) {
                        response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                        return;
                    }
                }
            }
        }
    });

    client.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy() {
        @Override
        public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
            // Honor 'keep-alive' header
            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")) {
                    try {
                        return Long.parseLong(value) * 1000;
                    } catch (NumberFormatException ignore) {
                    }
                }
            }

            long keepAlive = super.getKeepAliveDuration(response, context);
            if (keepAlive == -1) {
                keepAlive = _defaultKeepAliveDurationMS;
            }
            return keepAlive;
        }
    });

    return client;
}