Example usage for org.apache.http.params HttpConnectionParams setTcpNoDelay

List of usage examples for org.apache.http.params HttpConnectionParams setTcpNoDelay

Introduction

In this page you can find the example usage for org.apache.http.params HttpConnectionParams setTcpNoDelay.

Prototype

public static void setTcpNoDelay(HttpParams httpParams, boolean z) 

Source Link

Usage

From source file:com.DGSD.DGUtils.Http.BetterHttp.java

public static void setupHttpClient() {
    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, socketTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);
    HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams, httpUserAgent);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    if (DiagnosticUtils.ANDROID_API_LEVEL >= 7) {
        schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    } else {/*from www . j  a va2s . c  o m*/
        // used to work around a bug in Android 1.6:
        // http://code.google.com/p/android/issues/detail?id=1946
        // TODO: is there a less rigorous workaround for this?
        schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
    }

    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);
    httpClient = new DefaultHttpClient(cm, httpParams);
}

From source file:simple.crawler.http.HttpClientFactory.java

public static DefaultHttpClient createNewDefaultHttpClient() {
    ///* ww w  .j ava2s.  c  o m*/
    HttpParams params = new BasicHttpParams();

    //Determines the connection timeout
    HttpConnectionParams.setConnectionTimeout(params, 1 * 60 * 1000);

    //Determines the socket timeout
    HttpConnectionParams.setSoTimeout(params, 1 * 60 * 1000);

    //Determines whether stale connection check is to be used
    HttpConnectionParams.setStaleCheckingEnabled(params, false);

    //The Nagle's algorithm tries to conserve bandwidth by minimizing the number of segments that are sent. 
    //When application wish to decrease network latency and increase performance, they can disable Nagle's algorithm (that is enable TCP_NODELAY)
    //Data will be sent earlier, at the cost of an increase in bandwidth consumption
    HttpConnectionParams.setTcpNoDelay(params, true);

    //
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUserAgent(params,
            "Mozilla/5.0 (Windows; U; Windows NT 6.1; ru; rv:1.9.2.4) Gecko/20100513 Firefox/3.6.4");

    //Create and initialize scheme registry
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
    PoolingClientConnectionManager pm = new PoolingClientConnectionManager(schemeRegistry);

    //
    DefaultHttpClient httpclient = new DefaultHttpClient(pm, params);
    //ConnManagerParams.setMaxTotalConnections(params, MAX_HTTP_CONNECTION);
    //ConnManagerParams.setMaxConnectionsPerRoute(params, defaultConnPerRoute);
    //ConnManagerParams.setTimeout(params, 1 * 60 * 1000);
    httpclient.getParams().setParameter("http.conn-manager.max-total", MAX_HTTP_CONNECTION);
    ConnPerRoute defaultConnPerRoute = new ConnPerRoute() {
        public int getMaxForRoute(HttpRoute route) {
            return 4;
        }
    };
    httpclient.getParams().setParameter("http.conn-manager.max-per-route", defaultConnPerRoute);
    httpclient.getParams().setParameter("http.conn-manager.timeout", 1 * 60 * 1000L);
    httpclient.getParams().setParameter("http.protocol.allow-circular-redirects", true);
    httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);

    //
    HttpRequestRetryHandler retryHandler = new HttpRequestRetryHandler() {
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            if (executionCount > 2) {
                return false;
            }
            if (exception instanceof NoHttpResponseException) {
                return true;
            }
            if (exception instanceof SSLHandshakeException) {
                return false;
            }
            HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
            if (!(request instanceof HttpEntityEnclosingRequest)) {
                return true;
            }
            return false;
        }
    };
    httpclient.setHttpRequestRetryHandler(retryHandler);

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

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

    httpclient.addRequestInterceptor(requestInterceptor);
    httpclient.addResponseInterceptor(responseInterceptor);
    httpclient.setRedirectStrategy(new DefaultRedirectStrategy());

    return httpclient;
}

From source file:com.twotoasters.android.hoot.HootTransportHttpClient.java

@Override
public void setup(Hoot hoot) {
    HttpParams params = new BasicHttpParams();
    ConnManagerParams.setMaxTotalConnections(params, 10);
    ConnManagerParams.setTimeout(params, hoot.getTimeout());
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpConnectionParams.setConnectionTimeout(params, hoot.getTimeout());
    HttpConnectionParams.setSoTimeout(params, hoot.getTimeout());
    HttpConnectionParams.setTcpNoDelay(params, true);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
    sslSocketFactory.setHostnameVerifier(hoot.getSSLHostNameVerifier());
    schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));

    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
    mClient = new DefaultHttpClient(cm, params);
    if (hoot.isBasicAuth()) {
        mClient.getCredentialsProvider().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(hoot.getBasicAuthUsername(), hoot.getBasicAuthPassword()));
    }//from  ww w  .  j a  v a2 s  . c  o m
}

From source file:com.emc.vipr.services.s3.ViPRS3HttpClient.java

public ViPRS3HttpClient(ViPRS3Config viprConfig) {
    super(viprConfig.getClientConfiguration(), new SmartHttpClient(viprConfig.toSmartClientConfig()), null);

    ClientConfiguration azConfig = viprConfig.getClientConfiguration();
    HttpParams httpClientParams = httpClient.getParams();

    HttpConnectionParams.setConnectionTimeout(httpClientParams, azConfig.getConnectionTimeout());
    HttpConnectionParams.setSoTimeout(httpClientParams, azConfig.getSocketTimeout());
    HttpConnectionParams.setStaleCheckingEnabled(httpClientParams, true);
    HttpConnectionParams.setTcpNoDelay(httpClientParams, true);

    int socketSendBufferSizeHint = azConfig.getSocketBufferSizeHints()[0];
    int socketReceiveBufferSizeHint = azConfig.getSocketBufferSizeHints()[1];
    if (socketSendBufferSizeHint > 0 || socketReceiveBufferSizeHint > 0) {
        HttpConnectionParams.setSocketBufferSize(httpClientParams,
                Math.max(socketSendBufferSizeHint, socketReceiveBufferSizeHint));
    }/*  www.ja v a  2 s. c o  m*/

    ClientConnectionManager connectionManager = httpClient.getConnectionManager();
    ((SmartHttpClient) httpClient).setRedirectStrategy(new LocationHeaderNotRequiredRedirectStrategy());

    try {
        Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory());
        SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getDefault(),
                SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
        Scheme https = new Scheme("https", 443, sf);
        SchemeRegistry sr = connectionManager.getSchemeRegistry();
        sr.register(http);
        sr.register(https);
    } catch (NoSuchAlgorithmException e) {
        throw new AmazonClientException("Unable to access default SSL context", e);
    }

    /*
     * If SSL cert checking for endpoints has been explicitly disabled,
     * register a new scheme for HTTPS that won't cause self-signed certs to
     * error out.
     */
    if (System.getProperty(SDKGlobalConfiguration.DISABLE_CERT_CHECKING_SYSTEM_PROPERTY) != null) {
        Scheme sch = new Scheme("https", 443, new TrustingSocketFactory());
        httpClient.getConnectionManager().getSchemeRegistry().register(sch);
    }

    /* Set proxy if configured */
    String proxyHost = azConfig.getProxyHost();
    int proxyPort = azConfig.getProxyPort();
    if (proxyHost != null && proxyPort > 0) {
        log.info("Configuring Proxy. Proxy Host: " + proxyHost + " " + "Proxy Port: " + proxyPort);
        HttpHost proxyHttpHost = new HttpHost(proxyHost, proxyPort);
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHttpHost);

        String proxyUsername = azConfig.getProxyUsername();
        String proxyPassword = azConfig.getProxyPassword();
        String proxyDomain = azConfig.getProxyDomain();
        String proxyWorkstation = azConfig.getProxyWorkstation();

        if (proxyUsername != null && proxyPassword != null) {
            ((SmartHttpClient) httpClient).getCredentialsProvider().setCredentials(
                    new AuthScope(proxyHost, proxyPort),
                    new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain));
        }

        // Add a request interceptor that sets up proxy authentication pre-emptively if configured
        if (azConfig.isPreemptiveBasicProxyAuth()) {
            ((SmartHttpClient) httpClient).addRequestInterceptor(new PreemptiveProxyAuth(proxyHttpHost), 0);
        }
    }
}

From source file:org.openiot.gsn.http.rest.RestRemoteWrapper.java

private HttpParams getHttpClientParams(int timeout) {
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
    HttpProtocolParams.setUseExpectContinue(params, true);
    HttpConnectionParams.setTcpNoDelay(params, false);
    HttpConnectionParams.setSocketBufferSize(params, 8192);
    HttpConnectionParams.setStaleCheckingEnabled(params, true);
    HttpConnectionParams.setConnectionTimeout(params, 30 * 1000); // Set the connection time to 30s
    HttpConnectionParams.setSoTimeout(params, timeout);
    HttpProtocolParams.setUserAgent(params, "GSN-HTTP-CLIENT");
    return params;
}

From source file:com.bai.android.data.arcamera.DownloadContent.java

/**
 * The method that carries out the download and saving of the file to the according path 
 *///from   w  w  w  . java  2 s.  co m
public void downloadFile() throws Exception {
    ManageFileService manageFileService = new ManageFileService(localFileLocation);
    if (manageFileService.cardChecks() == true) {
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 20000);
        HttpConnectionParams.setSoTimeout(httpParameters, 15000);
        HttpConnectionParams.setTcpNoDelay(httpParameters, true);

        DefaultHttpClient client = new DefaultHttpClient(httpParameters);

        HttpGet request = new HttpGet(downloadUrl.toString());

        //get path for file save and prepare output stream to write the file;

        FileOutputStream fileOutput = new FileOutputStream(manageFileService.createFileForDownload());

        // Get the response
        HttpResponse response = client.execute(request);

        //start getting the data from the url input stream
        InputStream inputStream = response.getEntity().getContent();

        //create a buffer
        byte[] buffer = new byte[1024];
        int bufferLength = 0; //used to store a temporary size of the buffer

        //read through the input buffer and write the contents to the file
        while ((bufferLength = inputStream.read(buffer)) > 0) {
            //add the data in the buffer to the file in the file output stream
            fileOutput.write(buffer, 0, bufferLength);
        }
        //close the output stream when done
        fileOutput.close();
    } else {
        //TODO toast error
    }
    if (manageFileService.fileExists() == true) {
        String zipFile = localFileLocation;
        Decompress d = new Decompress(zipFile, unzipLocation);
        d.unzip();
        manageFileService.deleteFile();
    } else {
        //TODO toast error
    }
}

From source file:cn.ctyun.amazonaws.http.HttpClientFactory.java

/**
 * Creates a new HttpClient object using the specified AWS
 * ClientConfiguration to configure the client.
 *
 * @param config/*from  ww  w  .java 2 s.c o m*/
 *            Client configuration options (ex: proxy settings, connection
 *            limits, etc).
 *
 * @return The new, configured HttpClient.
 */
public HttpClient createHttpClient(ClientConfiguration config) {
    /* Set HTTP client parameters */
    HttpParams httpClientParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpClientParams, config.getConnectionTimeout());
    HttpConnectionParams.setSoTimeout(httpClientParams, config.getSocketTimeout());
    HttpConnectionParams.setStaleCheckingEnabled(httpClientParams, true);
    HttpConnectionParams.setTcpNoDelay(httpClientParams, true);

    int socketSendBufferSizeHint = config.getSocketBufferSizeHints()[0];
    int socketReceiveBufferSizeHint = config.getSocketBufferSizeHints()[1];
    if (socketSendBufferSizeHint > 0 || socketReceiveBufferSizeHint > 0) {
        HttpConnectionParams.setSocketBufferSize(httpClientParams,
                Math.max(socketSendBufferSizeHint, socketReceiveBufferSizeHint));
    }

    /* Set connection manager */
    ThreadSafeClientConnManager connectionManager = ConnectionManagerFactory
            .createThreadSafeClientConnManager(config, httpClientParams);
    DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, httpClientParams);
    httpClient.setRedirectStrategy(new LocationHeaderNotRequiredRedirectStrategy());

    try {
        Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory());

        SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getDefault(),
                SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
        Scheme https = new Scheme("https", 443, sf);

        SchemeRegistry sr = connectionManager.getSchemeRegistry();
        sr.register(http);
        sr.register(https);
    } catch (NoSuchAlgorithmException e) {
        throw new AmazonClientException("Unable to access default SSL context", e);
    }

    /*
     * If SSL cert checking for endpoints has been explicitly disabled,
     * register a new scheme for HTTPS that won't cause self-signed certs to
     * error out.
     */
    if (System.getProperty("com.amazonaws.sdk.disableCertChecking") != null) {
        Scheme sch = new Scheme("https", 443, new TrustingSocketFactory());
        httpClient.getConnectionManager().getSchemeRegistry().register(sch);
    }

    /* Set proxy if configured */
    String proxyHost = config.getProxyHost();
    int proxyPort = config.getProxyPort();
    if (proxyHost != null && proxyPort > 0) {
        AmazonHttpClient.log
                .info("Configuring Proxy. Proxy Host: " + proxyHost + " " + "Proxy Port: " + proxyPort);
        HttpHost proxyHttpHost = new HttpHost(proxyHost, proxyPort);
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHttpHost);

        String proxyUsername = config.getProxyUsername();
        String proxyPassword = config.getProxyPassword();
        String proxyDomain = config.getProxyDomain();
        String proxyWorkstation = config.getProxyWorkstation();

        if (proxyUsername != null && proxyPassword != null) {
            httpClient.getCredentialsProvider().setCredentials(new AuthScope(proxyHost, proxyPort),
                    new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain));
        }
    }

    return httpClient;
}

From source file:com.sinacloud.scs.http.HttpClientFactory.java

/**
 * Creates a new HttpClient object using the specified AWS
 * ClientConfiguration to configure the client.
 *
 * @param config//from   w  w  w . ja  v a  2s  .  c  om
 *            Client configuration options (ex: proxy settings, connection
 *            limits, etc).
 *
 * @return The new, configured HttpClient.
 */
@SuppressWarnings("deprecation")
public HttpClient createHttpClient(ClientConfiguration config) {
    /* Set HTTP client parameters */
    HttpParams httpClientParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpClientParams, config.getConnectionTimeout());
    HttpConnectionParams.setSoTimeout(httpClientParams, config.getSocketTimeout());
    HttpConnectionParams.setStaleCheckingEnabled(httpClientParams, true);
    HttpConnectionParams.setTcpNoDelay(httpClientParams, true);

    int socketSendBufferSizeHint = config.getSocketBufferSizeHints()[0];
    int socketReceiveBufferSizeHint = config.getSocketBufferSizeHints()[1];
    if (socketSendBufferSizeHint > 0 || socketReceiveBufferSizeHint > 0) {
        HttpConnectionParams.setSocketBufferSize(httpClientParams,
                Math.max(socketSendBufferSizeHint, socketReceiveBufferSizeHint));
    }

    PoolingClientConnectionManager connectionManager = ConnectionManagerFactory
            .createPoolingClientConnManager(config, httpClientParams);
    SdkHttpClient httpClient = new SdkHttpClient(connectionManager, httpClientParams);
    if (config.getMaxErrorRetry() > 0)
        httpClient.setHttpRequestRetryHandler(SdkHttpRequestRetryHandler.Singleton);
    //        httpClient.setRedirectStrategy(new LocationHeaderNotRequiredRedirectStrategy());

    try {
        Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);
        SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getDefault(),
                SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);

        Scheme https = new Scheme("https", sf, 443);
        SchemeRegistry sr = connectionManager.getSchemeRegistry();
        sr.register(http);
        sr.register(https);
    } catch (NoSuchAlgorithmException e) {
        throw new SCSClientException("Unable to access default SSL context", e);
    }

    //        /* 
    //         * If SSL cert checking for endpoints has been explicitly disabled,
    //         * register a new scheme for HTTPS that won't cause self-signed certs to
    //         * error out.
    //         */
    //        if (System.getProperty(DISABLE_CERT_CHECKING_SYSTEM_PROPERTY) != null) {
    Scheme sch = new Scheme("https", 443, new TrustingSocketFactory());
    httpClient.getConnectionManager().getSchemeRegistry().register(sch);
    //        }

    /* Set proxy if configured */
    String proxyHost = config.getProxyHost();
    int proxyPort = config.getProxyPort();
    if (proxyHost != null && proxyPort > 0) {
        //            AmazonHttpClient.log.info("Configuring Proxy. Proxy Host: " + proxyHost + " " + "Proxy Port: " + proxyPort);
        HttpHost proxyHttpHost = new HttpHost(proxyHost, proxyPort);
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHttpHost);

        String proxyUsername = config.getProxyUsername();
        String proxyPassword = config.getProxyPassword();
        String proxyDomain = config.getProxyDomain();
        String proxyWorkstation = config.getProxyWorkstation();

        if (proxyUsername != null && proxyPassword != null) {
            httpClient.getCredentialsProvider().setCredentials(new AuthScope(proxyHost, proxyPort),
                    new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain));
        }
    }

    return httpClient;
}

From source file:me.xiaopan.android.gohttp.HttpClientManager.java

public HttpClientManager(SchemeRegistry schemeRegistry) {
    BasicHttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setTcpNoDelay(httpParams, true); //?TCP
    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); //Http??
    HttpProtocolParams.setUserAgent(httpParams, DEFAULT_USER_AGENT); //?
    httpContext = new SyncBasicHttpContext(new BasicHttpContext()); //?Http
    httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(httpParams, schemeRegistry), httpParams);
    httpClient.addRequestInterceptor(new GzipProcessRequestInterceptor());
    httpClient.addRequestInterceptor(new AddRequestHeaderRequestInterceptor(getHeaderMap()));
    httpClient.addResponseInterceptor(new GzipProcessResponseInterceptor());
    httpClient/*from   w  ww .j av a 2s.  c om*/
            .setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES, DEFAULT_RETRY_SLEEP_TIME_MILLIS));
    clientHeaderMap = new HashMap<String, String>();
    setTimeout(DEFAULT_TIMEOUT);
    setMaxConnections(DEFAULT_MAX_CONNECTIONS);
    setSocketBufferSize(DEFAULT_SOCKET_BUFFER_SIZE);
}