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

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

Introduction

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

Prototype

public static void setStaleCheckingEnabled(HttpParams httpParams, boolean z) 

Source Link

Usage

From source file:org.fourthline.cling.transport.impl.apache.StreamClientImpl.java

public StreamClientImpl(StreamClientConfigurationImpl configuration) throws InitializationException {
    this.configuration = configuration;

    HttpProtocolParams.setContentCharset(globalParams, getConfiguration().getContentCharset());
    HttpProtocolParams.setUseExpectContinue(globalParams, false);

    // These are some safety settings, we should never run into these timeouts as we
    // do our own expiration checking
    HttpConnectionParams.setConnectionTimeout(globalParams,
            (getConfiguration().getTimeoutSeconds() + 5) * 1000);
    HttpConnectionParams.setSoTimeout(globalParams, (getConfiguration().getTimeoutSeconds() + 5) * 1000);

    HttpConnectionParams.setStaleCheckingEnabled(globalParams, getConfiguration().getStaleCheckingEnabled());
    if (getConfiguration().getSocketBufferSize() != -1)
        HttpConnectionParams.setSocketBufferSize(globalParams, getConfiguration().getSocketBufferSize());

    // Only register 80, not 443 and SSL
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    clientConnectionManager = new ThreadSafeClientConnManager(globalParams, registry);
    //clientConnectionManager.setMaxTotal(getConfiguration().getMaxTotalConnections());
    //clientConnectionManager.setDefaultMaxPerRoute(getConfiguration().getMaxTotalPerRoute());

    httpClient = new DefaultHttpClient(clientConnectionManager, globalParams);
    if (getConfiguration().getRequestRetryCount() != -1) {
        httpClient.setHttpRequestRetryHandler(
                new DefaultHttpRequestRetryHandler(getConfiguration().getRequestRetryCount(), false));
    }/*from www  .  j  a  v a2 s .  c om*/
}

From source file:org.jets3t.service.utils.signedurl.GatekeeperClientUtils.java

/**
 * Prepares objects for HTTP communications with the Gatekeeper servlet.
 * @return/*ww  w  . j  a  va 2 s.  co  m*/
 */
private HttpClient initHttpConnection() {
    // Set client parameters.
    HttpParams params = RestUtils.createDefaultHttpParams();
    HttpProtocolParams.setUserAgent(params, ServiceUtils.getUserAgentDescription(userAgentDescription));

    // Set connection parameters.
    HttpConnectionParams.setConnectionTimeout(params, connectionTimeout);
    HttpConnectionParams.setSoTimeout(params, connectionTimeout);
    HttpConnectionParams.setStaleCheckingEnabled(params, false);

    DefaultHttpClient httpClient = new DefaultHttpClient(params);
    // Replace default error retry handler.
    httpClient.setHttpRequestRetryHandler(new RestUtils.JetS3tRetryHandler(maxRetryCount, null));

    // httpClient.getParams().setAuthenticationPreemptive(true);
    httpClient.setCredentialsProvider(credentialsProvider);

    return httpClient;
}

From source file:com.appassit.http.AndroidHttpClient.java

/**
 * Create a new HttpClient with reasonable defaults (which you can update).
 * /*from   w  ww .  j av a2  s.c  o  m*/
 * @param userAgent
 *            to report in your HTTP requests
 * @param context
 *            to use for caching SSL sessions (may be null for no caching)
 * @return AndroidHttpClient for you to use for all your requests.
 */
public static AndroidHttpClient newInstance(String userAgent, Context context) {
    HttpParams params = new BasicHttpParams();
    // Turn off stale checking. Our connections break all the time anyway,
    // and it's not worth it to pay the penalty of checking every time.
    HttpConnectionParams.setStaleCheckingEnabled(params, false);

    // Default connection and socket timeout of 20 seconds. Tweak to taste.
    HttpConnectionParams.setConnectionTimeout(params, 20000);
    HttpConnectionParams.setSoTimeout(params, 20000);
    HttpConnectionParams.setSocketBufferSize(params, 8192);

    // Increase max total connection to 60
    ConnManagerParams.setMaxTotalConnections(params, 60);
    // Increase default max connection per route to 20
    ConnPerRouteBean connPerRoute = new ConnPerRouteBean(20);
    // Increase max connections for localhost:80 to 20
    HttpHost localhost = new HttpHost("locahost", 80);
    connPerRoute.setMaxForRoute(new HttpRoute(localhost), 20);
    ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);

    // Don't handle redirects -- return them to the caller. Our code
    // often wants to re-POST after a redirect, which we must do ourselves.
    HttpClientParams.setRedirecting(params, false);

    // Use a session cache for SSL sockets
    // SSLSessionCache sessionCache = context == null ? null : new SSLSessionCache(context);
    // SSLCertificateSocketFactory.getDefault (30 * 1000);

    // Set the specified user agent and register standard protocols.
    HttpProtocolParams.setUserAgent(params, userAgent);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

    ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry);

    // We use a factory method to modify superclass initialization
    // parameters without the funny call-a-static-method dance.
    return new AndroidHttpClient(manager, params);
}

From source file:com.android.mms.service.http.NetworkAwareHttpClient.java

/**
 * Create a new HttpClient with reasonable defaults (which you can update).
 *
 * @param userAgent to report in your HTTP requests
 * @param context to use for caching SSL sessions (may be null for no caching)
 * @return AndroidHttpClient for you to use for all your requests.
 *//*from  w w  w .  j  av  a 2 s  .  c  om*/
public static NetworkAwareHttpClient newInstance(String userAgent, Context context, NameResolver resolver,
        boolean shouldUseIpv6) {
    HttpParams params = new BasicHttpParams();

    // Turn off stale checking.  Our connections break all the time anyway,
    // and it's not worth it to pay the penalty of checking every time.
    HttpConnectionParams.setStaleCheckingEnabled(params, false);

    HttpConnectionParams.setConnectionTimeout(params, SOCKET_OPERATION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, SOCKET_OPERATION_TIMEOUT);
    HttpConnectionParams.setSocketBufferSize(params, 8192);

    // Don't handle redirects -- return them to the caller.  Our code
    // often wants to re-POST after a redirect, which we must do ourselves.
    HttpClientParams.setRedirecting(params, false);

    // Use a session cache for SSL sockets
    SSLSessionCache sessionCache = context == null ? null : new SSLSessionCache(context);

    // Set the specified user agent and register standard protocols.
    HttpProtocolParams.setUserAgent(params, userAgent);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https",
            SSLCertificateSocketFactory.getHttpSocketFactory(SOCKET_OPERATION_TIMEOUT, sessionCache), 443));

    /*
     * CHANGE FOR MmsService: using a different ClientConnectionManager which
     * uses a custom name resolver and can specify address type
     */
    ClientConnectionManager manager = new NetworkAwareThreadSafeClientConnManager(params, schemeRegistry,
            resolver, shouldUseIpv6);

    // We use a factory method to modify superclass initialization
    // parameters without the funny call-a-static-method dance.
    return new NetworkAwareHttpClient(manager, params);
}

From source file:com.android.callstat.common.net.MyHttpClient.java

/**
 * Create a new HttpClient with reasonable defaults (which you can update).
 * //from  w w  w  . j  a va 2 s .co m
 * @param userAgent
 *            to report in your HTTP requests
 * @param context
 *            to use for caching SSL sessions (may be null for no caching)
 * @return AndroidHttpClient for you to use for all your requests.
 */
public static MyHttpClient newInstance(String userAgent, Context context) {
    HttpParams params = new BasicHttpParams();
    HttpLog.v("AndroidHttpClient newInstance#########1111");
    // Turn off stale checking. Our connections break all the time anyway,
    // and it's not worth it to pay the penalty of checking every time.
    HttpConnectionParams.setStaleCheckingEnabled(params, false);

    // Default connection and socket timeout of 20 seconds. Tweak to taste.
    HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);
    HttpConnectionParams.setSoTimeout(params, 20 * 1000);
    HttpConnectionParams.setSocketBufferSize(params, 2048);

    // Don't handle redirects -- return them to the caller. Our code
    // often wants to re-POST after a redirect, which we must do ourselves.
    HttpClientParams.setRedirecting(params, true);
    // Use a session cache for SSL sockets
    // SSLSessionCache sessionCache = context == null ? null : new
    // SSLSessionCache(context);

    // Set the specified user agent and register standard protocols.
    HttpProtocolParams.setUserAgent(params, userAgent);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    // schemeRegistry.register(new Scheme("https", new
    // DummySSLSocketFactory(),443));
    // schemeRegistry.register(new Scheme("https",
    // SSLCertificateSocketFactory.getHttpSocketFactory(30 * 1000,
    // sessionCache), 443));
    ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry);

    // We use a factory method to modify superclass initialization
    // parameters without the funny call-a-static-method dance.
    return new MyHttpClient(manager, params);
}

From source file:com.github.rnewson.couchdb.lucene.HttpClientFactory.java

public static synchronized HttpClient getInstance() throws MalformedURLException {
    if (instance == null) {
        final HttpParams params = new BasicHttpParams();
        // protocol params.
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setUseExpectContinue(params, false);
        // connection params.
        HttpConnectionParams.setTcpNoDelay(params, true);
        HttpConnectionParams.setStaleCheckingEnabled(params, false);
        ConnManagerParams.setMaxTotalConnections(params, 1000);
        ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(1000));

        final SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 5984));
        schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
        final ClientConnectionManager cm = new ShieldedClientConnManager(
                new ThreadSafeClientConnManager(params, schemeRegistry));

        instance = new DefaultHttpClient(cm, params);

        if (INI != null) {
            final CredentialsProvider credsProvider = new BasicCredentialsProvider();
            final Iterator<?> it = INI.getKeys();
            while (it.hasNext()) {
                final String key = (String) it.next();
                if (!key.startsWith("lucene.") && key.endsWith(".url")) {
                    final URL url = new URL(INI.getString(key));
                    if (url.getUserInfo() != null) {
                        credsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort()),
                                new UsernamePasswordCredentials(url.getUserInfo()));
                    }//w w  w. ja  v a 2 s . c om
                }
            }
            instance.setCredentialsProvider(credsProvider);
            instance.addRequestInterceptor(new PreemptiveAuthenticationRequestInterceptor(), 0);
        }
    }
    return instance;
}

From source file:uk.co.unclealex.googleauth.ApacheHttpTransport.java

/**
 * Creates a new instance of the Apache HTTP client that is used by the
 * {@link #ApacheHttpTransport()} constructor.
 *
 * <p>//from w w w  .  ja  v  a 2 s.  c  om
 * Use this constructor if you want to customize the default Apache HTTP client. Settings:
 * </p>
 * <ul>
 * <li>The client connection manager is set to {@link ThreadSafeClientConnManager}.</li>
 * <li>The socket buffer size is set to 8192 using
 * {@link HttpConnectionParams#setSocketBufferSize}.</li>
 * <li><The retry mechanism is turned off by setting
 * {@code new DefaultHttpRequestRetryHandler(0, false)}</li>
 * </ul>
 *
 * @return new instance of the Apache HTTP client
 * @since 1.6
 */
public static DefaultHttpClient newDefaultHttpClient() {
    // Turn off stale checking. Our connections break all the time anyway,
    // and it's not worth it to pay the penalty of checking every time.
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setStaleCheckingEnabled(params, false);
    HttpConnectionParams.setSocketBufferSize(params, 8192);
    ConnManagerParams.setMaxTotalConnections(params, 200);
    ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(20));
    // See http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(params, registry);
    DefaultHttpClient defaultHttpClient = new DefaultHttpClient(connectionManager, params);
    defaultHttpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0, false));
    return defaultHttpClient;
}

From source file:com.amazonaws.http.HttpClientFactory.java

/**
 * Creates a new HttpClient object using the specified AWS
 * ClientConfiguration to configure the client.
 *
 * @param config//  w  w w.  ja v  a2s  .com
 *            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);
    HttpConnectionParams.setSoKeepalive(httpClientParams, config.useTcpKeepAlive());

    int socketSendBufferSizeHint = config.getSocketBufferSizeHints()[0];
    int socketReceiveBufferSizeHint = config.getSocketBufferSizeHints()[1];
    if (socketSendBufferSizeHint > 0 || socketReceiveBufferSizeHint > 0) {
        HttpConnectionParams.setSocketBufferSize(httpClientParams,
                Math.max(socketSendBufferSizeHint, socketReceiveBufferSizeHint));
    }
    final SSLContext sslContext = createSSLContext(config);
    SSLSocketFactory sslSocketFactory = config.getApacheHttpClientConfig().getSslSocketFactory();
    if (sslSocketFactory == null) {
        sslSocketFactory = new SdkTLSSocketFactory(sslContext, SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
    }

    PoolingClientConnectionManager connectionManager = ConnectionManagerFactory
            .createPoolingClientConnManager(config, httpClientParams, sslSocketFactory);

    SdkHttpClient httpClient = new SdkHttpClient(connectionManager, httpClientParams);
    httpClient.setHttpRequestRetryHandler(HttpRequestNoRetryHandler.Singleton);
    httpClient.setRedirectStrategy(new NeverFollowRedirectStrategy());

    if (config.getConnectionMaxIdleMillis() > 0) {
        httpClient
                .setKeepAliveStrategy(new SdkConnectionKeepAliveStrategy(config.getConnectionMaxIdleMillis()));
    }

    if (config.getLocalAddress() != null) {
        ConnRouteParams.setLocalAddress(httpClientParams, config.getLocalAddress());
    }

    Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory());
    Scheme https = new Scheme("https", 443, sslSocketFactory);
    SchemeRegistry sr = connectionManager.getSchemeRegistry();
    sr.register(http);
    sr.register(https);

    /*
     * 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));
        }

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

    /* Accept Gzip response if configured */
    if (config.useGzip()) {

        httpClient.addRequestInterceptor(new HttpRequestInterceptor() {

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

        });

        httpClient.addResponseInterceptor(new HttpResponseInterceptor() {

            @Override
            public void process(final HttpResponse response, final HttpContext context)
                    throws HttpException, IOException {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    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;
                            }
                        }
                    }
                }
            }

        });
    }

    return httpClient;
}