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.teleal.cling.transport.impl.apache.StreamClientImpl.java

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

    ConnManagerParams.setMaxTotalConnections(globalParams, getConfiguration().getMaxTotalConnections());
    HttpConnectionParams.setConnectionTimeout(globalParams,
            getConfiguration().getConnectionTimeoutSeconds() * 1000);
    HttpConnectionParams.setSoTimeout(globalParams, getConfiguration().getDataReadTimeoutSeconds() * 1000);
    HttpProtocolParams.setContentCharset(globalParams, getConfiguration().getContentCharset());
    if (getConfiguration().getSocketBufferSize() != -1) {

        // Android configuration will set this to 8192 as its httpclient is
        // based/*  w  ww. jav  a  2s .c  o  m*/
        // on a random pre 4.0.1 snapshot whose BasicHttpParams do not set a
        // default value for socket buffer size.
        // This will also avoid OOM on the HTC Thunderbolt where default
        // size is 2Mb (!):
        // http://stackoverflow.com/questions/5358014/android-httpclient-oom-on-4g-lte-htc-thunderbolt

        HttpConnectionParams.setSocketBufferSize(globalParams, getConfiguration().getSocketBufferSize());
    }
    HttpConnectionParams.setStaleCheckingEnabled(globalParams, getConfiguration().getStaleCheckingEnabled());

    // This is a pretty stupid API...
    // https://issues.apache.org/jira/browse/HTTPCLIENT-805
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); // The
    // 80
    // here
    // is...
    // useless
    clientConnectionManager = new ThreadSafeClientConnManager(globalParams, registry);
    httpClient = new DefaultHttpClient(clientConnectionManager, globalParams);
    if (getConfiguration().getRequestRetryCount() != -1) {
        httpClient.setHttpRequestRetryHandler(
                new DefaultHttpRequestRetryHandler(getConfiguration().getRequestRetryCount(), false));
    }

    /*
     * // TODO: Ugh! And it turns out that by default it doesn't even use
     * persistent connections properly!
     * 
     * @Override protected ConnectionReuseStrategy
     * createConnectionReuseStrategy() { return new
     * NoConnectionReuseStrategy(); }
     * 
     * @Override protected ConnectionKeepAliveStrategy
     * createConnectionKeepAliveStrategy() { return new
     * ConnectionKeepAliveStrategy() { public long
     * getKeepAliveDuration(HttpResponse httpResponse, HttpContext
     * httpContext) { return 0; } }; }
     * httpClient.removeRequestInterceptorByClass(RequestConnControl.class);
     */
}

From source file:com.github.diogochbittencourt.googleplaydownloader.downloader.impl.AndroidHttpClient.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.  ja  va  2 s.com
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);

    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);

    Object sessionCache = null;
    // Use a session cache for SSL sockets -- Froyo only
    if (null != context && null != sSslSessionCacheClass) {
        Constructor<?> ct;
        try {
            ct = sSslSessionCacheClass.getConstructor(Context.class);
            sessionCache = ct.newInstance(context);
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    // 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));
    SocketFactory sslCertificateSocketFactory = null;
    if (null != sessionCache) {
        Method getHttpSocketFactoryMethod;
        try {
            getHttpSocketFactoryMethod = SSLCertificateSocketFactory.class
                    .getDeclaredMethod("getHttpSocketFactory", Integer.TYPE, sSslSessionCacheClass);
            sslCertificateSocketFactory = (SocketFactory) getHttpSocketFactoryMethod.invoke(null,
                    SOCKET_OPERATION_TIMEOUT, sessionCache);
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    if (null == sslCertificateSocketFactory) {
        sslCertificateSocketFactory = SSLSocketFactory.getSocketFactory();
    }
    schemeRegistry.register(new Scheme("https", sslCertificateSocketFactory, 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.example.refapp.utils.http.GzipHttpClient.java

/**
 * Create a new HttpClient with reasonable defaults (which you can update).
 *
 * @param userAgent to report in your HTTP requests.
 * @return AndroidHttpClient for you to use for all your requests.
 *///  w w  w.  j  av a 2  s .  c om
public static GzipHttpClient newInstance(final String userAgent) {
    final 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, 40 * 1000);
    HttpConnectionParams.setSoTimeout(params, 40 * 1000);
    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);

    // Set the specified user agent and register standard protocols.
    if (userAgent != null) {
        HttpProtocolParams.setUserAgent(params, userAgent);
    }
    final SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    final 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 GzipHttpClient(manager, params);
}

From source file:com.bt.download.android.core.HttpFetcher.java

public Object[] fetch(boolean gzip) throws IOException {
    HttpHost httpHost = new HttpHost(uri.getHost(), uri.getPort());
    HttpGet httpGet = new HttpGet(uri);
    httpGet.addHeader("Connection", "close");

    HttpParams params = httpGet.getParams();
    HttpConnectionParams.setConnectionTimeout(params, timeout);
    HttpConnectionParams.setSoTimeout(params, timeout);
    HttpConnectionParams.setStaleCheckingEnabled(params, true);
    HttpConnectionParams.setTcpNoDelay(params, true);
    HttpClientParams.setRedirecting(params, true);
    HttpProtocolParams.setUseExpectContinue(params, false);
    HttpProtocolParams.setUserAgent(params, userAgent);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    try {// w  w  w . j a va 2  s . c  om

        HttpResponse response = (gzip ? DEFAULT_HTTP_CLIENT_GZIP : DEFAULT_HTTP_CLIENT).execute(httpHost,
                httpGet);

        if (response.getStatusLine().getStatusCode() < 200 || response.getStatusLine().getStatusCode() >= 300) {
            throw new IOException(
                    "bad status code, downloading file " + response.getStatusLine().getStatusCode());
        }

        Long date = Long.valueOf(0);

        Header[] headers = response.getAllHeaders();
        for (int i = 0; i < headers.length; i++) {
            if (headers[i].getName().startsWith("Last-Modified")) {
                try {
                    date = DateUtils.parseDate(headers[i].getValue()).getTime();
                } catch (Exception e) {
                }
                break;
            }
        }

        if (response.getEntity() != null) {
            if (gzip) {
                String str = EntityUtils.toString(response.getEntity());
                baos.write(str.getBytes());
            } else {
                response.getEntity().writeTo(baos);
            }
        }

        body = baos.toByteArray();

        if (body == null || body.length == 0) {
            throw new IOException("invalid response");
        }

        return new Object[] { body, date };

    } finally {
        try {
            baos.close();
        } catch (IOException e) {
        }
    }
}

From source file:com.autonomy.aci.client.transport.impl.HttpClientFactory.java

/**
 * Creates an instance of <tt>DefaultHttpClient</tt> with a <tt>ThreadSafeClientConnManager</tt>.
 * @return an implementation of the <tt>HttpClient</tt> interface.
 *///from w ww.  j a v  a  2s .c  o m
public HttpClient createInstance() {
    LOGGER.debug("Creating a new instance of DefaultHttpClient with configuration -> {}", toString());

    // Create the connection manager which will be default create the necessary schema registry stuff...
    final PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager();
    connectionManager.setMaxTotal(maxTotalConnections);
    connectionManager.setDefaultMaxPerRoute(maxConnectionsPerRoute);

    // Set the HTTP connection parameters (These are in the HttpCore JavaDocs, NOT the HttpClient ones)...
    final HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, connectionTimeout);
    HttpConnectionParams.setLinger(params, linger);
    HttpConnectionParams.setSocketBufferSize(params, socketBufferSize);
    HttpConnectionParams.setSoKeepalive(params, soKeepAlive);
    HttpConnectionParams.setSoReuseaddr(params, soReuseAddr);
    HttpConnectionParams.setSoTimeout(params, soTimeout);
    HttpConnectionParams.setStaleCheckingEnabled(params, staleCheckingEnabled);
    HttpConnectionParams.setTcpNoDelay(params, tcpNoDelay);

    // Create the HttpClient and configure the compression interceptors if required...
    final DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, params);

    if (useCompression) {
        httpClient.addRequestInterceptor(new RequestAcceptEncoding());
        httpClient.addResponseInterceptor(new DeflateContentEncoding());
    }

    return httpClient;
}

From source file:com.hardincoding.sonar.subsonic.service.SubsonicMusicService.java

private SubsonicMusicService() {
    // Create and initialize default HTTP parameters
    HttpParams params = new BasicHttpParams();
    ConnManagerParams.setMaxTotalConnections(params, 20);
    ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(20));
    HttpConnectionParams.setConnectionTimeout(params, SOCKET_CONNECT_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, SOCKET_READ_TIMEOUT_DEFAULT);

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

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

    // Create an HttpClient with the ThreadSafeClientConnManager.
    // This connection manager must be used if more than one thread will
    // be using the HttpClient.
    connManager = new ThreadSafeClientConnManager(params, schemeRegistry);
    mHttpClient = new DefaultHttpClient(connManager, params);

    // TODO Use HTTP Basic Auth
    // Configure preemptive HTTP Basic Authentication
    //      HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
    //          public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    //              AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
    //              CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(
    //                      ClientContext.CREDS_PROVIDER);
    //              HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
    //              
    //              if (authState.getAuthScheme() == null) {
    //                  AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
    //                  Credentials creds = credsProvider.getCredentials(authScope);
    //                  if (creds != null) {
    //                      authState.setAuthScheme(new BasicScheme());
    //                      authState.setCredentials(creds);
    //                  }
    //              }
    //          }    
    //      };//from  w w  w . java2  s  .c o  m
    //      mHttpClient.addRequestInterceptor(preemptiveAuth, 0);
}

From source file:com.fanfou.app.opensource.util.NetworkHelper.java

private static final HttpParams createHttpParams() {
    final HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setUseExpectContinue(params, false);
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    ConnManagerParams.setTimeout(params, NetworkHelper.SOCKET_TIMEOUT_MS);
    HttpConnectionParams.setConnectionTimeout(params, NetworkHelper.CONNECTION_TIMEOUT_MS);
    HttpConnectionParams.setSoTimeout(params, NetworkHelper.SOCKET_TIMEOUT_MS);

    ConnManagerParams.setMaxConnectionsPerRoute(params,
            new ConnPerRouteBean(NetworkHelper.MAX_TOTAL_CONNECTIONS));
    ConnManagerParams.setMaxTotalConnections(params, NetworkHelper.MAX_TOTAL_CONNECTIONS);

    HttpConnectionParams.setStaleCheckingEnabled(params, false);
    HttpConnectionParams.setTcpNoDelay(params, true);
    HttpConnectionParams.setSocketBufferSize(params, NetworkHelper.SOCKET_BUFFER_SIZE);
    HttpClientParams.setRedirecting(params, false);
    HttpProtocolParams.setUserAgent(params, "FanFou for Android/" + AppContext.appVersionName);
    return params;
}

From source file:org.mumod.util.HttpManager.java

public HttpParams getHttpParams() {
    final HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");

    HttpConnectionParams.setStaleCheckingEnabled(params, true);
    //        HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);
    HttpConnectionParams.setSoTimeout(params, DEFAULT_REQUEST_TIMEOUT);
    HttpConnectionParams.setSocketBufferSize(params, 2 * 8192);

    //        HttpClientParams.setRedirecting(params, true);

    HttpProtocolParams.setUserAgent(params, getUserAgent());
    HttpProtocolParams.setUseExpectContinue(params, false);

    return params;

}

From source file:com.google.pubsub.clients.common.MetricsHandler.java

private void initialize() {
    synchronized (this) {
        try {//from w w  w.  j  a v  a 2  s .c  o m
            HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
            JsonFactory jsonFactory = new JacksonFactory();
            GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
            if (credential.createScopedRequired()) {
                credential = credential.createScoped(
                        Collections.singletonList("https://www.googleapis.com/auth/cloud-platform"));
            }
            monitoring = new Monitoring.Builder(transport, jsonFactory, credential)
                    .setApplicationName("Cloud Pub/Sub Loadtest Framework").build();
            String zoneId;
            String instanceId;
            try {
                DefaultHttpClient httpClient = new DefaultHttpClient();
                httpClient.addRequestInterceptor(new RequestAcceptEncoding());
                httpClient.addResponseInterceptor(new ResponseContentEncoding());

                HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), 30000);
                HttpConnectionParams.setSoTimeout(httpClient.getParams(), 30000);
                HttpConnectionParams.setSoKeepalive(httpClient.getParams(), true);
                HttpConnectionParams.setStaleCheckingEnabled(httpClient.getParams(), false);
                HttpConnectionParams.setTcpNoDelay(httpClient.getParams(), true);

                SchemeRegistry schemeRegistry = httpClient.getConnectionManager().getSchemeRegistry();
                schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
                schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
                httpClient.setKeepAliveStrategy((response, ctx) -> 30);
                HttpGet zoneIdRequest = new HttpGet(
                        "http://metadata.google.internal/computeMetadata/v1/instance/zone");
                zoneIdRequest.setHeader("Metadata-Flavor", "Google");
                HttpResponse zoneIdResponse = httpClient.execute(zoneIdRequest);
                String tempZoneId = EntityUtils.toString(zoneIdResponse.getEntity());
                if (tempZoneId.lastIndexOf("/") >= 0) {
                    zoneId = tempZoneId.substring(tempZoneId.lastIndexOf("/") + 1);
                } else {
                    zoneId = tempZoneId;
                }
                HttpGet instanceIdRequest = new HttpGet(
                        "http://metadata.google.internal/computeMetadata/v1/instance/id");
                instanceIdRequest.setHeader("Metadata-Flavor", "Google");
                HttpResponse instanceIdResponse = httpClient.execute(instanceIdRequest);
                instanceId = EntityUtils.toString(instanceIdResponse.getEntity());
            } catch (IOException e) {
                log.info("Unable to connect to metadata server, assuming not on GCE, setting "
                        + "defaults for instance and zone.");
                instanceId = "local";
                zoneId = "us-east1-b"; // Must use a valid cloud zone even if running local.
            }

            monitoredResource.setLabels(
                    ImmutableMap.of("project_id", project, "instance_id", instanceId, "zone", zoneId));
            createMetrics();
        } catch (IOException e) {
            log.error("Unable to initialize MetricsHandler, trying again.", e);
            executor.execute(this::initialize);
        } catch (GeneralSecurityException e) {
            log.error("Unable to initialize MetricsHandler permanently, credentials error.", e);
        }
    }
}

From source file:org.alfresco.http.SharedHttpClientProvider.java

/**
 * See <a href="http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html">Connection management</a>.
 * //from www.j  a v a  2s. co m
 * @param maxNumberOfConnections        the maximum number of Http connections in the pool
 * @param connectionTimeoutMs           the time to wait for a connection from the pool before failure
 * @param socketTimeoutMs               the time to wait for data activity on a connection before failure
 * @param socketTtlMs                   the time for a socket to remain alive before being forcibly closed (0 for infinite)
 */
public SharedHttpClientProvider(int maxNumberOfConnections, int connectionTimeoutMs, int socketTimeoutMs,
        int socketTtlMs) {
    SSLSocketFactory sslSf = null;
    try {
        TrustStrategy sslTs = new TrustAnyTrustStrategy();
        sslSf = new SSLSocketFactory(sslTs, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (Throwable e) {
        throw new RuntimeException("Unable to construct HttpClientProvider.", e);
    }

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 8080, PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https", 443, sslSf));
    schemeRegistry.register(new Scheme("https", 80, sslSf));

    httpClientCM = new PoolingClientConnectionManager(schemeRegistry, (long) socketTtlMs,
            TimeUnit.MILLISECONDS);
    // Increase max total connections
    httpClientCM.setMaxTotal(maxNumberOfConnections);
    // Ensure that we don't throttle on a per-scheme basis (BENCH-45)
    httpClientCM.setDefaultMaxPerRoute(maxNumberOfConnections);

    httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, connectionTimeoutMs);
    HttpConnectionParams.setSoTimeout(httpParams, socketTimeoutMs);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setStaleCheckingEnabled(httpParams, true);
    HttpConnectionParams.setSoKeepalive(httpParams, true);

}