Example usage for org.apache.http.params BasicHttpParams setParameter

List of usage examples for org.apache.http.params BasicHttpParams setParameter

Introduction

In this page you can find the example usage for org.apache.http.params BasicHttpParams setParameter.

Prototype

public HttpParams setParameter(String str, Object obj) 

Source Link

Usage

From source file:com.pyj.http.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient.// w w w .  j av  a  2 s  .  co  m
 */
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);
    // ?cookie
    httpParams.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
    // httpParams.setParameter(ClientPNames.COOKIE_POLICY, "hupu.com");
    httpParams.setParameter(CookieSpecPNames.SINGLE_COOKIE_HEADER, true);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);

    if (Build.VERSION.SDK != null && Build.VERSION.SDK_INT > 13) {
        httpParams.setParameter("Connection", "close");
    }
    // HttpProtocolParams.setUserAgent(httpParams,
    // String.format("android-async-http/%s (http://loopj.com/android-async-http)",
    // VERSION));

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    // SSLSocketFactory ssl=getSSLSocketFactory();
    // schemeRegistry.register(new Scheme("https", ssl, 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);
            }
            if (!request.containsHeader(""))
                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()) {
                    // HupuLog.d("ResponseInterceptor",
                    // "key="+element.getName()+" value="+element.getValue());
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        //                     HupuLog.d("ResponseInterceptor", "gzip");
                        response.setEntity(new InflatingEntity(response.getEntity()));
                        // continue;
                    }

                }
            }
            Header[] headers = response.getHeaders(HEADER_DATE);
            if (headers != null) {
                for (int i = 0; i < headers.length; i++) {
                    if (headers[i].getName().equalsIgnoreCase(HEADER_DATE)) {
                        Date date = new java.util.Date(headers[i].getValue());
                        today = date.getTime();
                        // Calendar cal = new GregorianCalendar();
                    }
                }
            }

        }
    });

    httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES));

    threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool();

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

    // CookieStore cookieStore = new BasicCookieStore();
    // setCookieStore(cookieStore);

}

From source file:com.zuowuxuxi.asihttp.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient.//  w  w  w .  ja  v  a  2  s.  c  o m
 */
@SuppressWarnings("rawtypes")
public AsyncHttpClient(HttpHost hcProxyHost) {
    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, String.format("android-async-http/%s (http://loopj.com/android-async-http)", VERSION));
    //HttpProtocolParams.setUserAgent(httpParams, "Mozilla/5.0 (Linux; U; Android 2.3.7; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1");
    HttpProtocolParams.setUserAgent(httpParams, String.format(CONF.USER_AGENT));

    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());
    /*proxy*/
    //HttpHost hcProxyHost = new HttpHost("127.0.0.1", 8087, "http");
    if (hcProxyHost != null) {
        httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, hcProxyHost);
    }

    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        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() {
        public void process(HttpResponse response, HttpContext context) {
            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;
                    }
                }
            }
        }
    });

    httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES));

    threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool();

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

From source file:com.bnrc.http.AbHttpClient.java

/**
 * HTTP?/*from   w  ww .j a  v a 2s  .c om*/
 * @return
 */
public BasicHttpParams getHttpParams() {

    BasicHttpParams httpParams = new BasicHttpParams();

    // ??
    ConnPerRouteBean connPerRoute = new ConnPerRouteBean(30);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, connPerRoute);
    HttpConnectionParams.setStaleCheckingEnabled(httpParams, false);
    // ??????1
    ConnManagerParams.setTimeout(httpParams, mTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(DEFAULT_MAX_CONNECTIONS));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);
    // ???
    HttpConnectionParams.setSoTimeout(httpParams, mTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, mTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams, userAgent);
    //?
    HttpClientParams.setRedirecting(httpParams, false);
    HttpClientParams.setCookiePolicy(httpParams, CookiePolicy.BROWSER_COMPATIBILITY);
    httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, null);
    return httpParams;

}

From source file:cn.org.eshow.framwork.http.AbHttpClient.java

/**
 * HTTP??// w  w  w .ja  v  a  2 s .c  o  m
 * @return
 */
public BasicHttpParams getHttpParams() {

    BasicHttpParams httpParams = new BasicHttpParams();

    // ?
    ConnPerRouteBean connPerRoute = new ConnPerRouteBean(30);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, connPerRoute);
    HttpConnectionParams.setStaleCheckingEnabled(httpParams, false);
    // ?1
    ConnManagerParams.setTimeout(httpParams, mTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(DEFAULT_MAX_CONNECTIONS));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);
    // ??
    HttpConnectionParams.setSoTimeout(httpParams, mTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, mTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams, userAgent);
    //?
    HttpClientParams.setRedirecting(httpParams, false);
    HttpClientParams.setCookiePolicy(httpParams, CookiePolicy.BROWSER_COMPATIBILITY);
    httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, null);
    return httpParams;

}

From source file:com.rackspacecloud.client.cloudfiles.FilesClient.java

/**
 * //from  w w  w  .ja v  a2  s .  c  o  m
 * 
 * @param username
 *             
 * @param password
 *             
 * @param authUrl
 *             
 * @param account
 *             
 * @param connectionTimeOut
 *             ms
 */
public FilesClient(String username, String password, String authUrl, String account,
        final int connectionTimeOut) {
    this(new DefaultHttpClient() {
        protected HttpParams createHttpParams() {
            BasicHttpParams params = new BasicHttpParams();
            org.apache.http.params.HttpConnectionParams.setSoTimeout(params, connectionTimeOut);
            params.setParameter("http.socket.timeout", connectionTimeOut);
            return params;
        }

        @Override
        protected ClientConnectionManager createClientConnectionManager() {
            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
            schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
            return new ThreadSafeClientConnManager(createHttpParams(), schemeRegistry);
        }
    }, username, password, authUrl, account, connectionTimeOut);

}

From source file:API.amazon.mws.feeds.service.MarketplaceWebServiceClient.java

/**
 * Configure HttpClient with set of defaults as well as configuration
 * from MarketplaceWebServiceConfig instance
 *
 *///from   w  w w  . j a  v  a2s . c om
private HttpClient configureHttpClient(String applicationName, String applicationVersion) {

    // respect a user-provided User-Agent header as-is, but if none is provided
    // then generate one satisfying the MWS User-Agent requirements
    if (config.getUserAgent() == null) {
        config.setUserAgent(quoteAppName(applicationName), quoteAppVersion(applicationVersion),
                quoteAttributeValue("Java/" + System.getProperty("java.version") + "/"
                        + System.getProperty("java.class.version") + "/" + System.getProperty("java.vendor")),

                quoteAttributeName("Platform"),
                quoteAttributeValue("" + System.getProperty("os.name") + "/" + System.getProperty("os.arch")
                        + "/" + System.getProperty("os.version")),

                quoteAttributeName("MWSClientVersion"), quoteAttributeValue(mwsClientLibraryVersion));
    }

    defaultHeaders.add(new BasicHeader("X-Amazon-User-Agent", config.getUserAgent()));

    /* Set http client parameters */
    BasicHttpParams httpParams = new BasicHttpParams();

    httpParams.setParameter(CoreProtocolPNames.USER_AGENT, config.getUserAgent());

    /* Set connection parameters */
    HttpConnectionParams.setConnectionTimeout(httpParams, config.getConnectionTimeout());
    HttpConnectionParams.setSoTimeout(httpParams, config.getSoTimeout());
    HttpConnectionParams.setStaleCheckingEnabled(httpParams, true);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);

    /* Set connection manager */
    PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager();
    connectionManager.setMaxTotal(config.getMaxAsyncQueueSize());
    connectionManager.setDefaultMaxPerRoute(config.getMaxAsyncQueueSize());

    /* Set http client */
    httpClient = new DefaultHttpClient(connectionManager, httpParams);
    httpContext = new BasicHttpContext();

    /* Set proxy if configured */
    if (config.isSetProxyHost() && config.isSetProxyPort()) {
        log.info("Configuring Proxy. Proxy Host: " + config.getProxyHost() + "Proxy Port: "
                + config.getProxyPort());
        final HttpHost hostConfiguration = new HttpHost(config.getProxyHost(), config.getProxyPort(),
                (usesHttps(config.getServiceURL()) ? "https" : "http"));
        httpContext = new BasicHttpContext();
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, hostConfiguration);

        if (config.isSetProxyUsername() && config.isSetProxyPassword()) {
            credentialsProvider.setCredentials(new AuthScope(config.getProxyHost(), config.getProxyPort()),
                    new UsernamePasswordCredentials(config.getProxyUsername(), config.getProxyPassword()));
            httpContext.setAttribute(ClientContext.CREDS_PROVIDER, credentialsProvider);

        }

    }

    return httpClient;
}

From source file:com.amazonaws.mws.MarketplaceWebServiceClient.java

/**
 * Configure HttpClient with set of defaults as well as configuration
 * from MarketplaceWebServiceConfig instance
 *
 *//*w  w w .j ava  2s .  com*/
private HttpClient configureHttpClient(String applicationName, String applicationVersion) {

    // respect a user-provided User-Agent header as-is, but if none is provided
    // then generate one satisfying the MWS User-Agent requirements
    if (config.getUserAgent() == null) {
        config.setUserAgent(quoteAppName(applicationName), quoteAppVersion(applicationVersion),
                quoteAttributeValue("Java/" + System.getProperty("java.version") + "/"
                        + System.getProperty("java.class.version") + "/" + System.getProperty("java.vendor")),

                quoteAttributeName("Platform"),
                quoteAttributeValue("" + System.getProperty("os.name") + "/" + System.getProperty("os.arch")
                        + "/" + System.getProperty("os.version")),

                quoteAttributeName("MWSClientVersion"), quoteAttributeValue(mwsClientLibraryVersion));
    }

    defaultHeaders.add(new BasicHeader("X-Amazon-User-Agent", config.getUserAgent()));

    /* Set http client parameters */
    BasicHttpParams httpParams = new BasicHttpParams();

    httpParams.setParameter(CoreProtocolPNames.USER_AGENT, config.getUserAgent());

    /* Set connection parameters */
    HttpConnectionParams.setConnectionTimeout(httpParams, config.getConnectionTimeout());
    HttpConnectionParams.setSoTimeout(httpParams, config.getSoTimeout());
    HttpConnectionParams.setStaleCheckingEnabled(httpParams, true);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);

    /* Set connection manager */
    PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager();
    connectionManager.setMaxTotal(config.getMaxAsyncQueueSize());
    connectionManager.setDefaultMaxPerRoute(config.getMaxAsyncQueueSize());

    /* Set http client */
    httpClient = new DefaultHttpClient(connectionManager, httpParams);
    httpContext = new BasicHttpContext();

    /* Set proxy if configured */
    if (config.isSetProxyHost() && config.isSetProxyPort()) {
        String proxyProtocol = null;
        if (config.isSetProxyProtocol()) {
            //User explicitly set how to talk to proxy
            proxyProtocol = config.getProxyProtocol().toString().toLowerCase();
        } else {
            // assume that the mws endpoint url determines the protocol
            // for the proxy as well
            proxyProtocol = usesHttps(config.getServiceURL()) ? "https" : "http";
        }
        log.info("Configuring Proxy. Proxy Host: " + config.getProxyHost() + " Proxy Port: "
                + config.getProxyPort() + " Proxy protocol: " + proxyProtocol);
        final HttpHost hostConfiguration = new HttpHost(config.getProxyHost(), config.getProxyPort(),
                proxyProtocol);
        httpContext = new BasicHttpContext();
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, hostConfiguration);

        if (config.isSetProxyUsername() && config.isSetProxyPassword()) {
            credentialsProvider.setCredentials(new AuthScope(config.getProxyHost(), config.getProxyPort()),
                    new UsernamePasswordCredentials(config.getProxyUsername(), config.getProxyPassword()));
            httpContext.setAttribute(ClientContext.CREDS_PROVIDER, credentialsProvider);

        }

    }

    return httpClient;
}