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:com.polyvi.xface.http.XHttpWorker.java

/**
 * ?httpclient// w ww.  j  a v a2s. c  om
 */
private void initHttpClient() {
    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.setConnectionTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams, "xface");

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", XSSLSocketFactory.getSocketFactory(), 443));
    schemeRegistry.register(new Scheme("https", XSSLSocketFactory.getSocketFactory(), 8443));
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);
    mHttpClient = new DefaultHttpClient(cm, httpParams);
    mHttpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : mClientHeaderMap.keySet()) {
                request.addHeader(header, mClientHeaderMap.get(header));
            }
        }
    });

    mHttpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            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;
                    }
                }
            }
        }
    });
    mHttpContext = new SyncBasicHttpContext(new BasicHttpContext());
}

From source file:jp.takuo.android.mmsreq.Request.java

protected HttpResponse requestHttp() throws ClientProtocolException, IOException {
    HttpGet reqGet = new HttpGet(REQUEST_URL);
    DefaultHttpClient client = new DefaultHttpClient();
    HttpParams params = client.getParams();
    Log.d(LOG_TAG, "Proxy: " + mProxyHost + ":" + PROXY_PORT);
    ConnRouteParams.setDefaultProxy(params, new HttpHost(mProxyHost, PROXY_PORT));
    Log.d(LOG_TAG, "UserAgent: " + mUserAgent);
    HttpProtocolParams.setUserAgent(params, mUserAgent);
    reqGet.setParams(params);/*from   w  w  w .  j a v a2 s. c  om*/
    Log.d(LOG_TAG, "HTTP Get: " + REQUEST_URL);
    return (HttpResponse) client.execute(reqGet);
}

From source file:com.gistlabs.mechanize.impl.MechanizeAgent.java

/**
 *
 * @param userAgent The value to set User-Agent HTTP parameter to for requests
 * @return/* w  ww. j  av  a  2s  .  com*/
 */
public MechanizeAgent setUserAgent(final String userAgent) {
    HttpProtocolParams.setUserAgent(this.client.getParams(), userAgent);
    return this;
}

From source file:com.lurencun.cfuture09.androidkit.http.async.AsyncHttp.java

public AsyncHttp() {
    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.setConnectionTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams, Version.ANDROIDKIT_NAME);

    // ??/*w  w w  . ja v a  2 s.co m*/
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }

            for (Entry<String, String> entry : clientHeaderMap.entrySet()) {
                request.addHeader(entry.getKey(), entry.getValue());
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            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;
                    }
                }
            }
        }
    });

    httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES));

    threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool(new AKThreadFactory());

    requestMap = new WeakHashMap<Context, List<WeakReference<Future<?>>>>();
    clientHeaderMap = new HashMap<String, String>();
}

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.
 *///from  w  ww .  j  a v a2 s  . co m
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.bbxiaoqu.api.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   ww w  . j  av  a2s .  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);

    // 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:cn.xdf.thinkutils.http2.AsyncHttpClient.java

public AsyncHttpClient() {
    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.setConnectionTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams,
            String.format("thinkandroid/%s (http://www.thinkandroid.cn)", VERSION));

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override//from   w  w w  .j a v a2s . c o m
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                request.addHeader(header, clientHeaderMap.get(header));
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            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;
                    }
                }
            }
        }
    });

    httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES));

    threadPool = new ThreadPoolExecutor(DEFAULT_CORE_POOL_SIZE, DEFAULT_MAXIMUM_POOL_SIZE,
            DEFAULT_KEEP_ALIVETIME, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(3),
            new ThreadPoolExecutor.CallerRunsPolicy());

    requestMap = new WeakHashMap<Context, List<WeakReference<Future<?>>>>();
    clientHeaderMap = new HashMap<String, String>();
}

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:cloudMe.CloudMeAPI.java

private DefaultHttpClient getConnection() {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), false);
    HttpProtocolParams.setUserAgent(httpClient.getParams(), USER_AGENT_INFO);
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(host, 80, "os@xcerion.com", "Digest"),
            new UsernamePasswordCredentials(userName, pass)); // Encrypts password & username
    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);
            if (authState.getAuthScheme() == null) {
                if (creds != null && scheme != null) {
                    authState.setAuthScheme(scheme);
                    authState.setCredentials(creds);
                } else {
                    scheme = authState.getAuthScheme();
                }/*from w w  w  .  j  a v  a  2s.c o  m*/
            }
        }
    };
    httpClient.addRequestInterceptor(preemptiveAuth, 0);
    return httpClient;

}

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

/**
 * Create a new HttpClient with reasonable defaults (which you can update).
 * //from  w w  w  .  j  a  v 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);
}