Example usage for org.apache.http.impl.conn.tsccm ThreadSafeClientConnManager ThreadSafeClientConnManager

List of usage examples for org.apache.http.impl.conn.tsccm ThreadSafeClientConnManager ThreadSafeClientConnManager

Introduction

In this page you can find the example usage for org.apache.http.impl.conn.tsccm ThreadSafeClientConnManager ThreadSafeClientConnManager.

Prototype

@Deprecated
public ThreadSafeClientConnManager(final HttpParams params, final SchemeRegistry schreg) 

Source Link

Document

Creates a new thread safe connection manager.

Usage

From source file:com.sogeti.droidnetworking.NetworkEngine.java

public void init(final Context context, final Map<String, String> headers) {
    this.context = context;

    // Setup a queue for operations
    sharedNetworkQueue = Executors.newFixedThreadPool(2);

    // Init the memory cache, if the default memory cache size shouldn't be used, set the
    // size using setMemoryCacheSize before calling init
    if (memoryCacheSize > 0) {
        memoryCache = new LruCache<String, CacheEntry>(memoryCacheSize) {
            protected int sizeOf(final String key, final CacheEntry entry) {
                return entry.size();
            }//  w ww. ja va2s . c  o m
        };
    } else {
        memoryCache = null;
    }

    // Init the disk cache, if the default disk cache size shouldn't be used, set the
    // size using setDiskCacheSize before calling init
    if (diskCacheSize > 0) {
        try {
            diskCache = DiskLruCache.open(context.getCacheDir(), DISK_CACHE_VERSION, DISK_CACHE_VALUE_COUNT,
                    diskCacheSize);
        } catch (IOException e) {
            diskCache = null;
        }
    } else {
        diskCache = null;
    }

    // Setup HTTP
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), httpPort));

    // Setup HTTPS (accept all certificates)
    HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
    socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
    schemeRegistry.register(new Scheme("https", socketFactory, httpsPort));

    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, connectionTimeout);
    HttpConnectionParams.setSoTimeout(params, socketTimeout);

    ThreadSafeClientConnManager connManager = new ThreadSafeClientConnManager(params, schemeRegistry);

    httpClient = new DefaultHttpClient(connManager, params);

    if (headers == null) {
        this.headers = new HashMap<String, String>();
    } else {
        this.headers = headers;
    }

    if (!this.headers.containsKey("User-Agent")) {
        try {
            PackageInfo packageInfo = this.context.getPackageManager()
                    .getPackageInfo(this.context.getPackageName(), 0);
            this.headers.put("User-Agent", packageInfo.packageName + "/" + packageInfo.versionName);
        } catch (NameNotFoundException e) {
            this.headers.put("User-Agent", "Unknown/0.0");
        }
    }
}

From source file:com.madrobot.net.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient./*  ww  w .  j  a  v a 2 s.c o  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);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    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));
    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 (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();
            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.uroad.net.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("uroad-android-httpclient/%s (http://www.u-road.com/)", VERSION));
    //Scheme??"http""https"???
    //??socket??java.net.SocketSchemeRegistry?Schemes?
    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??
    //?/*from w  w w .j a  v  a2 s  . c o  m*/
    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 (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.neudesic.azureservicebustest.asynchttp.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient./*from ww  w . j  av a2  s.c om*/
 */
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("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));
    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 (String header : clientHeaderMap.keySet()) {
                request.addHeader(header, clientHeaderMap.get(header));
            }

            request.addHeader("Accept", "*/*"); // SVG 5/8/2013 - intercept this to add for our API
        }
    });

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

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

From source file:org.urbanstew.soundcloudapi.SoundCloudAPI.java

private void initialize() {
    HttpClient client = new DefaultHttpClient();

    httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(client.getParams(),
            client.getConnectionManager().getSchemeRegistry()), client.getParams());

}

From source file:com.webwoz.wizard.server.components.MTinGoogle.java

public void initializeConnection(String proxyHostName, int proxyHostPort) {
    SchemeRegistry supportedSchemes = new SchemeRegistry();
    // Register the "http" and "https" protocol schemes, they are
    // required by the default operator to look up socket factories.
    supportedSchemes.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    supportedSchemes.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    // prepare parameters
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUseExpectContinue(params, true);

    ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, supportedSchemes);

    httpClient = new DefaultHttpClient(ccm, params);

    HttpHost proxyHost = new HttpHost(proxyHostName, proxyHostPort);

    httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost);
}

From source file:com.wialon.remote.ApacheSdkHttpClient.java

public DefaultHttpClient getHttpClient(int timeoutMs) {
    if (timeoutMs == 0 || timeoutMs == DEFAULT_SOCKET_TIMEOUT)
        return defaultHttpClient;
    else {/*  w  w w.  j a v  a  2 s.  c om*/
        BasicHttpParams params = getBasicHttpParams(timeoutMs);
        ThreadSafeClientConnManager connectionManager = new ThreadSafeClientConnManager(params, registry);
        return new DefaultHttpClient(connectionManager, params);
    }
}

From source file:org.ofbiz.testtools.seleniumxml.RemoteRequest.java

public void runTest() {

    ClientConnectionManager ccm = new ThreadSafeClientConnManager(defaultParameters, supportedSchemes);
    //  new SingleClientConnManager(getParams(), supportedSchemes);

    DefaultHttpClient client = new DefaultHttpClient(ccm, defaultParameters);
    client.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy());

    ////  ww w .  j a v  a 2 s . c o m
    // We first try to login with the loginAs to set the session.
    // Then we call the remote service.
    //
    HttpEntity entity = null;
    ResponseHandler<String> responseHandler = null;
    try {
        BasicHttpContext localContext = new BasicHttpContext();
        // Create a local instance of cookie store
        CookieStore cookieStore = new BasicCookieStore();
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

        Header sessionHeader = null;

        if (this.loginAsUrl != null) {

            String loginAsUri = this.host + this.loginAsUrl;
            String loginAsParamString = "?" + this.loginAsUserParam + "&" + this.loginAsPasswordParam;

            HttpGet req2 = new HttpGet(loginAsUri + loginAsParamString);
            System.out.println("loginAsUrl:" + loginAsUri + loginAsParamString);

            req2.setHeader("Connection", "Keep-Alive");
            HttpResponse rsp = client.execute(req2, localContext);

            Header[] headers = rsp.getAllHeaders();
            for (int i = 0; i < headers.length; i++) {
                Header hdr = headers[i];
                String headerValue = hdr.getValue();
                if (headerValue.startsWith("JSESSIONID")) {
                    sessionHeader = hdr;
                }
                System.out.println("login: " + hdr.getName() + " : " + hdr.getValue());
            }
            List<Cookie> cookies = cookieStore.getCookies();
            System.out.println("cookies.size(): " + cookies.size());
            for (int i = 0; i < cookies.size(); i++) {
                System.out.println("Local cookie(0): " + cookies.get(i));
            }
        }
        //String paramString2 = "USERNAME=" + this.parent.getUserName()
        //                   + "&PASSWORD=" + this.parent.getPassword();
        //String thisUri2 = this.host + "/eng/control/login?" + paramString2;
        //HttpGet req2 = new HttpGet ( thisUri2 );
        //req2.setHeader("Connection","Keep-Alive");
        //HttpResponse rsp = client.execute(req2, localContext);

        //Header sessionHeader = null;
        //Header[] headers = rsp.getAllHeaders();
        //for (int i=0; i<headers.length; i++) {
        //    Header hdr = headers[i];
        //    String headerValue = hdr.getValue();
        //    if (headerValue.startsWith("JSESSIONID")) {
        //        sessionHeader = hdr;
        //    }
        //    System.out.println(headers[i]);
        //    System.out.println(hdr.getName() + " : " + hdr.getValue());
        //}

        //List<Cookie> cookies = cookieStore.getCookies();
        //System.out.println("cookies.size(): " + cookies.size());
        //for (int i = 0; i < cookies.size(); i++) {
        //    System.out.println("Local cookie(0): " + cookies.get(i));
        //}
        if (HttpHandleMode.equals(this.responseHandlerMode)) {

        } else {
            responseHandler = new JsonResponseHandler(this);
        }

        String paramString = urlEncodeArgs(this.inMap, false);

        String thisUri = null;
        if (sessionHeader != null) {
            String sessionHeaderValue = sessionHeader.getValue();
            int pos1 = sessionHeaderValue.indexOf("=");
            int pos2 = sessionHeaderValue.indexOf(";");
            String sessionId = sessionHeaderValue.substring(pos1 + 1, pos2);
            thisUri = this.host + this.requestUrl + ";jsessionid=" + sessionId + "?" + paramString;
        } else {
            thisUri = this.host + this.requestUrl + "?" + paramString;
        }
        //String sessionHeaderValue = sessionHeader.getValue();
        //int pos1 = sessionHeaderValue.indexOf("=");
        //int pos2 = sessionHeaderValue.indexOf(";");
        //String sessionId = sessionHeaderValue.substring(pos1 + 1, pos2);
        //System.out.println("sessionId: " + sessionId);
        //String thisUri = this.host + this.requestUrl + ";jsessionid=" + sessionId + "?"  + paramString;
        //String thisUri = this.host + this.requestUrl + "?"  + paramString;
        System.out.println("thisUri: " + thisUri);

        HttpGet req = new HttpGet(thisUri);
        if (sessionHeader != null) {
            req.setHeader(sessionHeader);
        }

        String responseBody = client.execute(req, responseHandler, localContext);
        /*
        entity = rsp.getEntity();
                
        System.out.println("----------------------------------------");
        System.out.println(rsp.getStatusLine());
        Header[] headers = rsp.getAllHeaders();
        for (int i=0; i<headers.length; i++) {
        System.out.println(headers[i]);
        }
        System.out.println("----------------------------------------");
                
        if (entity != null) {
        System.out.println(EntityUtils.toString(rsp.getEntity()));
        }
        */
    } catch (HttpResponseException e) {
        System.out.println(e.getMessage());
    } catch (IOException e) {
        System.out.println(e.getMessage());
    } finally {
        // If we could be sure that the stream of the entity has been
        // closed, we wouldn't need this code to release the connection.
        // However, EntityUtils.toString(...) can throw an exception.

        // if there is no entity, the connection is already released
        try {
            if (entity != null)
                entity.consumeContent(); // release connection gracefully
        } catch (IOException e) {
            System.out.println("in 'finally'  " + e.getMessage());
        }

    }
    return;
}

From source file:com.madrobot.net.client.XMLRPCClient.java

/**
 * XMLRPCClient constructor. Creates new instance based on server URI (Code contributed by sgayda2 from issue #17,
 * and by erickok from ticket #10)/*  w w w.  j  a v  a 2 s  .c o m*/
 * 
 * @param XMLRPC
 *            server URI
 */
public XMLRPCClient(URI uri) {
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", new PlainSocketFactory(), 80));
    registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

    postMethod = new HttpPost(uri);
    postMethod.addHeader("Content-Type", "text/xml");

    // WARNING
    // I had to disable "Expect: 100-Continue" header since I had
    // two second delay between sending http POST request and POST body
    httpParams = postMethod.getParams();
    HttpProtocolParams.setUseExpectContinue(httpParams, false);
    this.client = new DefaultHttpClient(new ThreadSafeClientConnManager(httpParams, registry), httpParams);
}

From source file:org.gege.caldavsyncadapter.caldav.CaldavFacade.java

protected HttpClient getHttpClient() {

    HttpParams params = new BasicHttpParams();
    params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
    params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
    params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", new PlainSocketFactory(), 80));
    registry.register(new Scheme("https",
            (trustAll ? EasySSLSocketFactory.getSocketFactory() : SSLSocketFactory.getSocketFactory()), 443));
    DefaultHttpClient client = new DefaultHttpClient(new ThreadSafeClientConnManager(params, registry), params);

    return client;
}