Example usage for org.apache.http.params HttpProtocolParams setUserAgent

List of usage examples for org.apache.http.params HttpProtocolParams setUserAgent

Introduction

In this page you can find the example usage for org.apache.http.params HttpProtocolParams setUserAgent.

Prototype

public static void setUserAgent(HttpParams httpParams, String str) 

Source Link

Usage

From source file:net.peterkuterna.android.apps.devoxxsched.util.SyncUtils.java

/**
 * Generate and return a {@link HttpClient} configured for general use,
 * including setting an application-specific user-agent string.
 *///from  w  ww . j av a 2 s  .  c o m
public static HttpClient getHttpClient(Context context) {
    final HttpParams params = new BasicHttpParams();

    // Use generous timeouts for slow mobile networks
    HttpConnectionParams.setConnectionTimeout(params, 200 * SECOND_IN_MILLIS);
    HttpConnectionParams.setSoTimeout(params, 200 * SECOND_IN_MILLIS);

    HttpConnectionParams.setSocketBufferSize(params, 8192);
    HttpProtocolParams.setUserAgent(params, buildUserAgent(context));

    final HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    final SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
    sslSocketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
    final SchemeRegistry schemeReg = new SchemeRegistry();
    schemeReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeReg.register(new Scheme("https", sslSocketFactory, 443));
    final ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(params, schemeReg);
    final DefaultHttpClient client = new DefaultHttpClient(connectionManager, params);

    client.addRequestInterceptor(new HttpRequestInterceptor() {
        public void process(HttpRequest request, HttpContext context) {
            // Add header to accept gzip content
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
        }
    });

    client.addResponseInterceptor(new HttpResponseInterceptor() {
        public void process(HttpResponse response, HttpContext context) {
            // Inflate any responses compressed with gzip
            final HttpEntity entity = response.getEntity();
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(response.getEntity()));
                        break;
                    }
                }
            }
        }
    });

    return client;
}

From source file:ch.cyberduck.core.http.HTTP4Session.java

/**
 * Create new HTTP client with default configuration and custom trust manager.
 *
 * @return A new instance of a default HTTP client.
 *//*  w ww . j av  a 2 s .c om*/
protected AbstractHttpClient http() {
    if (null == http) {
        final HttpParams params = new BasicHttpParams();

        HttpProtocolParams.setVersion(params, org.apache.http.HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, getEncoding());
        HttpProtocolParams.setUserAgent(params, getUserAgent());

        AuthParams.setCredentialCharset(params, "ISO-8859-1");

        HttpConnectionParams.setTcpNoDelay(params, true);
        HttpConnectionParams.setSoTimeout(params, timeout());
        HttpConnectionParams.setSocketBufferSize(params, 8192);

        HttpClientParams.setRedirecting(params, true);
        HttpClientParams.setAuthenticating(params, true);

        SchemeRegistry registry = new SchemeRegistry();
        // Always register HTTP for possible use with proxy
        registry.register(new Scheme("http", host.getPort(), PlainSocketFactory.getSocketFactory()));
        if ("https".equals(this.getHost().getProtocol().getScheme())) {
            org.apache.http.conn.ssl.SSLSocketFactory factory = new SSLSocketFactory(
                    new CustomTrustSSLProtocolSocketFactory(this.getTrustManager()).getSSLContext(),
                    org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            registry.register(new Scheme(host.getProtocol().getScheme(), host.getPort(), factory));
        }
        if (Preferences.instance().getBoolean("connection.proxy.enable")) {
            final Proxy proxy = ProxyFactory.instance();
            if ("https".equals(this.getHost().getProtocol().getScheme())) {
                if (proxy.isHTTPSProxyEnabled(host)) {
                    ConnRouteParams.setDefaultProxy(params,
                            new HttpHost(proxy.getHTTPSProxyHost(host), proxy.getHTTPSProxyPort(host)));
                }
            }
            if ("http".equals(this.getHost().getProtocol().getScheme())) {
                if (proxy.isHTTPProxyEnabled(host)) {
                    ConnRouteParams.setDefaultProxy(params,
                            new HttpHost(proxy.getHTTPProxyHost(host), proxy.getHTTPProxyPort(host)));
                }
            }
        }
        ClientConnectionManager manager = new SingleClientConnManager(registry);
        http = new DefaultHttpClient(manager, params);
        this.configure(http);
    }
    return http;
}

From source file:com.thistech.spotlink.util.HttpClientFactory.java

public HttpClient newInstance() {
    HttpClient client = new DefaultHttpClient();
    HttpParams httpParams = client.getParams();
    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);

    if (this.properties.containsKey("httpclient.timeout")) {
        int timeout = Integer.parseInt(this.properties.getProperty("httpclient.timeout"));
        HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
        HttpConnectionParams.setSoTimeout(httpParams, timeout);
    }//from   w ww.ja va2s.  com

    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRoute() {
        public int getMaxForRoute(HttpRoute route) {
            return Integer.parseInt(properties.getProperty("httpclient.conn-per-route", "5"));
        }
    });

    int totalConnections = Integer.parseInt(this.properties.getProperty("httpclient.total-connections", "100"));
    ConnManagerParams.setMaxTotalConnections(httpParams, totalConnections);

    String userAgent = this.properties.getProperty("httpclient.user-agent", "Mozilla/5.0");
    HttpProtocolParams.setUserAgent(httpParams, userAgent);

    String charset = this.properties.getProperty("httpclient.content-charset", "UTF-8");
    HttpProtocolParams.setContentCharset(httpParams, charset);

    ClientConnectionManager mgr = client.getConnectionManager();
    SchemeRegistry schemeRegistry = mgr.getSchemeRegistry();
    client = new DefaultHttpClient(new ThreadSafeClientConnManager(httpParams, schemeRegistry), httpParams);
    return client;
}

From source file:riddimon.android.asianetautologin.HttpManager.java

private HttpManager(Boolean debug, String version) {
    // Set basic data
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUseExpectContinue(params, true);
    HttpProtocolParams.setUserAgent(params, HttpUtils.userAgent);

    // Make pool//from   w ww.ja  va  2  s  .  c  o  m
    ConnPerRoute connPerRoute = new ConnPerRouteBean(12);
    ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);
    ConnManagerParams.setMaxTotalConnections(params, 20);

    // Set timeout
    HttpConnectionParams.setStaleCheckingEnabled(params, false);
    HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);
    HttpConnectionParams.setSoTimeout(params, 20 * 1000);
    HttpConnectionParams.setSocketBufferSize(params, 8192);

    // Some client params
    HttpClientParams.setRedirecting(params, false);

    // Register http/s schemas!
    SchemeRegistry schReg = new SchemeRegistry();
    schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    if (debug) {
        // Install the all-trusting trust manager
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustManagers = new X509TrustManager[1];
        trustManagers[0] = new TrustAllManager();

        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustManagers, null);
            schReg.register(new Scheme("https", (SocketFactory) sc.getSocketFactory(), 443));
        } catch (Exception e) {
            ;
        }
    } else {
        schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

    }
    ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);
    client = new DefaultHttpClient(conMgr, params);

}

From source file:com.cttapp.bby.mytlc.layer8apps.ConnectionManager.java

/************
 *   PURPOSE: Creates a new instance of client
 *   ARGUMENTS: null/*ww w .ja v a 2  s . com*/
 *   RETURNS: ConnectionManager
 *   AUTHOR: Devin Collins <agent14709@gmail.com>
 *************/
private ConnectionManager() {
    try {
        SSLSocketFactory factory = new SimpleSSLSocketFactory(null);
        factory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
        HttpProtocolParams.setUserAgent(params, "MyTLC-Sync");

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", factory, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        // Create a new connection for our client
        client = new DefaultHttpClient(ccm, params);
    } catch (Exception ex) {
        client = new DefaultHttpClient();
    }
}

From source file:org.vsearchd.crawler.backend.BackendSessionHTTP.java

public synchronized void connect() {
    httpclient = new DefaultHttpClient();
    httppost = new HttpPost();

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUseExpectContinue(params, false);
    HttpProtocolParams.setUserAgent(params, "vsearchd::backend-worker");
    HttpConnectionParams.setStaleCheckingEnabled(params, false);

    httppost.setParams(params);//from  www.  j a va2  s.c  o  m
}

From source file:com.devoteam.srit.xmlloader.http.test.HttpLoaderClient.java

public void run() {

    Long beginThreadResponse = System.currentTimeMillis(); // top chrono des reponses
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setHttpElementCharset(params, "UTF-8");
    HttpProtocolParams.setContentCharset(params, "text");
    HttpProtocolParams.setUserAgent(params, "XmlLoader");
    HttpProtocolParams.setUseExpectContinue(params, true);

    try {/*  ww w  . j a  v a 2s. c  o  m*/
        http.receiveResponse("GET", "D:/XMLloader/testPileHttp/src/test/HttpLoader/", params, 5000000);
        Long endThreadResponse = System.currentTimeMillis();
        timeThreadResponse = endThreadResponse - beginThreadResponse; // calcul de la dure du processus de reception des msg
        Long totalTime = timeThreadRequest + timeThreadResponse; // calcul de la dure du programme
        System.out.println("transaction number : " + 5000000 * 2);
        System.out.println("All transaction time : " + (long) totalTime / 1000 + " s"
        /* + "trans/ms: "+(float)totalTime/50*/);
        System.out.println("number transaction /s: " + (float) (5000000 * 2) / (totalTime / 1000));
    } catch (IOException e) {
        System.out.println("connection error");
    } catch (HttpException e) {
    }
}

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 {/*  w w  w .  j  a  v  a 2s  .co 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() {
    ////from   w  ww  .  j av a 2  s.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;
}