Example usage for org.apache.http.conn.ssl SSLSocketFactory getSocketFactory

List of usage examples for org.apache.http.conn.ssl SSLSocketFactory getSocketFactory

Introduction

In this page you can find the example usage for org.apache.http.conn.ssl SSLSocketFactory getSocketFactory.

Prototype

public static SSLSocketFactory getSocketFactory() throws SSLInitializationException 

Source Link

Document

Obtains default SSL socket factory with an SSL context based on the standard JSSE trust material (cacerts file in the security properties directory).

Usage

From source file:com.mnxfst.testing.activities.http.AbstractHTTPRequestActivity.java

/**
 * @see com.mnxfst.testing.activities.TSPlanActivity#initialize(com.mnxfst.testing.plan.config.TSPlanConfigOption)
 *//*from w w  w .  jav  a 2  s  . com*/
public void initialize(TSPlanConfigOption cfg) throws TSPlanActivityExecutionException {

    if (cfg == null)
        throw new TSPlanActivityExecutionException("Failed to initialize activity '" + this.getClass().getName()
                + "' due to missing configuration options");

    /////////////////////////////////////////////////////////////////////////////////////////
    // fetch scheme, host, port and path

    this.scheme = (String) cfg.getOption(CFG_OPT_SCHEME);
    if (this.scheme == null || this.scheme.isEmpty())
        throw new TSPlanActivityExecutionException(
                "Required config option '" + CFG_OPT_SCHEME + "' missing for activity '" + getName() + "'");

    this.host = (String) cfg.getOption(CFG_OPT_HOST);
    if (this.host == null || this.host.isEmpty())
        throw new TSPlanActivityExecutionException(
                "Requied config option '" + CFG_OPT_HOST + "' missing for activity '" + getName() + "'");

    String portStr = (String) cfg.getOption(CFG_OPT_PORT);
    if (portStr != null && !portStr.isEmpty()) {
        try {
            this.port = Integer.parseInt(portStr.trim());
        } catch (NumberFormatException e) {
            throw new TSPlanActivityExecutionException(
                    "Failed to parse expected numerical value for config option '" + CFG_OPT_PORT
                            + "' for activity '" + getName() + "'");
        }
    }

    // fetch username and password
    this.basicAuthUsername = (String) cfg.getOption(CFG_OPT_BASIC_AUTH_USERNAME);
    this.basicAuthPassword = (String) cfg.getOption(CFG_OPT_BASIC_AUTH_PASSWORD);
    this.basicAuthHostScope = (String) cfg.getOption(CFG_OPT_BASIC_AUTH_HOST_SCOPE);

    String authPortScopeStr = (String) cfg.getOption(CFG_OPT_BASIC_AUTH_PORT_SCOPE);
    if (authPortScopeStr != null && !authPortScopeStr.trim().isEmpty()) {
        try {
            this.basicAuthPortScope = Integer.parseInt(authPortScopeStr.trim());
        } catch (NumberFormatException e) {
            throw new TSPlanActivityExecutionException(
                    "Failed to parse expected numerical value for config option '"
                            + CFG_OPT_BASIC_AUTH_PORT_SCOPE + "' for activity '" + getName() + "'");
        }
    }

    if (this.port <= 0)
        this.port = 80;

    this.path = (String) cfg.getOption(CFG_OPT_PATH);
    if (this.path == null || this.path.isEmpty())
        this.path = "/";

    String maxConnStr = (String) cfg.getOption(CFG_OPT_MAX_CONNECTIONS);
    if (maxConnStr != null && !maxConnStr.isEmpty()) {
        try {
            this.maxConnections = Integer.parseInt(maxConnStr);
        } catch (NumberFormatException e) {
            throw new TSPlanActivityExecutionException(
                    "Failed to parse expected numerical value for config option '" + CFG_OPT_MAX_CONNECTIONS
                            + "' for activity '" + getName() + "'");
        }
    }

    // initialize http host and context
    this.httpHost = new HttpHost(this.host, this.port);

    // URI builder
    try {

        // query parameters
        List<NameValuePair> qParams = new ArrayList<NameValuePair>();
        for (String key : cfg.getOptions().keySet()) {
            if (key.startsWith(REQUEST_PARAM_OPTION_PREFIX)) {
                String value = (String) cfg.getOption(key);
                String requestParameterName = key.substring(REQUEST_PARAM_OPTION_PREFIX.length(), key.length());
                qParams.add(new BasicNameValuePair(requestParameterName, value));

                if (logger.isDebugEnabled())
                    logger.debug("activity[name=" + getName() + ", id=" + getId() + ", requestParameter="
                            + requestParameterName + ", value=" + value + "]");
            }
        }

        this.destinationURI = URIUtils.createURI(this.scheme, this.host, this.port, this.path,
                URLEncodedUtils.format(qParams, this.contentChartset), null);

        // TODO handle post values

    } catch (URISyntaxException e) {
        throw new TSPlanActivityExecutionException("Failed to initialize uri for [scheme=" + this.scheme
                + ", host=" + this.host + ", port=" + this.port + ", path=" + this.path + "]");
    }

    httpRequestContext.setAttribute(ExecutionContext.HTTP_CONNECTION, clientConnection);
    httpRequestContext.setAttribute(ExecutionContext.HTTP_TARGET_HOST, httpHost);

    if (logger.isDebugEnabled())
        logger.debug("activity[name=" + getName() + ", id=" + getId() + ", maxConnections=" + maxConnections
                + ", scheme=" + scheme + ", host=" + host + ", port=" + port + ", path=" + path + "]");

    /////////////////////////////////////////////////////////////////////////////////////////

    /////////////////////////////////////////////////////////////////////////////////////////
    // protocol settings

    this.userAgent = (String) cfg.getOption(CFG_OPT_USER_AGENT);
    if (this.userAgent == null || this.userAgent.isEmpty())
        this.userAgent = "ptest-server";

    String protocolVersion = (String) cfg.getOption(CFG_OPT_HTTP_PROTOCOL_VERSION);
    if (protocolVersion != null && !protocolVersion.isEmpty()) {
        if (protocolVersion.equalsIgnoreCase("0.9"))
            this.httpVersion = HttpVersion.HTTP_0_9;
        else if (protocolVersion.equalsIgnoreCase("1.0"))
            this.httpVersion = HttpVersion.HTTP_1_0;
        else if (protocolVersion.equalsIgnoreCase("1.1"))
            this.httpVersion = HttpVersion.HTTP_1_1;
        else
            throw new TSPlanActivityExecutionException("Failed to parse http protocol version '"
                    + protocolVersion + "'. Valid value: 0.9, 1.0 and 1.1");
    }

    this.contentChartset = (String) cfg.getOption(CFG_OPT_CONTENT_CHARSET);
    if (this.contentChartset == null || this.contentChartset.isEmpty())
        this.contentChartset = "UTF-8";

    String expectContStr = (String) cfg.getOption(CFG_OPT_EXPECT_CONTINUE);
    if (expectContStr != null && !expectContStr.isEmpty()) {
        this.expectContinue = Boolean.parseBoolean(expectContStr.trim());
    }

    HttpProtocolParams.setUserAgent(httpParameters, userAgent);
    HttpProtocolParams.setVersion(httpParameters, httpVersion);
    HttpProtocolParams.setContentCharset(httpParameters, contentChartset);
    HttpProtocolParams.setUseExpectContinue(httpParameters, expectContinue);

    String httpProcStr = (String) cfg.getOption(CFG_OPT_HTTP_REQUEST_PROCESSORS);
    if (httpProcStr != null && !httpProcStr.isEmpty()) {
        List<HttpRequestInterceptor> interceptors = new ArrayList<HttpRequestInterceptor>();
        String[] procClasses = httpProcStr.split(",");
        if (procClasses != null && procClasses.length > 0) {
            for (int i = 0; i < procClasses.length; i++) {
                try {
                    Class<?> clazz = Class.forName(procClasses[i]);
                    interceptors.add((HttpRequestInterceptor) clazz.newInstance());

                    if (logger.isDebugEnabled())
                        logger.debug("activity[name=" + getName() + ", id=" + getId()
                                + ", httpRequestInterceptor=" + procClasses[i] + "]");
                } catch (Exception e) {
                    throw new TSPlanActivityExecutionException("Failed to instantiate http interceptor '"
                            + procClasses[i] + "' for activity '" + getName() + "'. Error: " + e.getMessage());
                }
            }
        }

        this.httpRequestResponseProcessor = new ImmutableHttpProcessor(
                (HttpRequestInterceptor[]) interceptors.toArray(EMPTY_HTTP_REQUEST_INTERCEPTOR_ARRAY));
        this.hasRequestResponseProcessors = true;
    }

    this.method = (String) cfg.getOption(CFG_OPT_METHOD);
    if (method == null || method.isEmpty())
        this.method = "GET";
    if (!method.equalsIgnoreCase("get") && !method.equalsIgnoreCase("post"))
        throw new TSPlanActivityExecutionException(
                "Invalid method '" + method + "' found for activity '" + getName() + "'");

    if (logger.isDebugEnabled())
        logger.debug("activity[name=" + getName() + ", id=" + getId() + ", method=" + method + ", user-agent="
                + userAgent + ", httpVersion=" + httpVersion + ", contentCharset=" + contentChartset
                + ", expectContinue=" + expectContinue + "]");

    /////////////////////////////////////////////////////////////////////////////////////////

    /////////////////////////////////////////////////////////////////////////////////////////
    // fetch proxy settings

    this.proxyUrl = (String) cfg.getOption(CFG_OPT_PROXY_URL);

    String proxyPortStr = (String) cfg.getOption(CFG_OPT_PROXY_PORT);
    if (proxyPortStr != null && !proxyPortStr.isEmpty()) {
        try {
            this.proxyPort = Integer.parseInt(proxyPortStr.trim());
        } catch (NumberFormatException e) {
            throw new TSPlanActivityExecutionException(
                    "Failed to parse expected numerical value for config option '" + CFG_OPT_PROXY_PORT
                            + "' for activity '" + getName() + "'");
        }
    }

    this.proxyUser = (String) cfg.getOption(CFG_OPT_PROXY_USER);
    this.proxyPassword = (String) cfg.getOption(CFG_OPT_PROXY_PASSWORD);

    if (proxyUrl != null && !proxyUrl.isEmpty()) {

        if (proxyPort > 0)
            this.proxyHost = new HttpHost(proxyUrl, proxyPort);
        else
            this.proxyHost = new HttpHost(proxyUrl);
    }

    if (logger.isDebugEnabled())
        logger.debug("activity[name=" + getName() + ", id=" + getId() + ", proxyUrl=" + proxyUrl
                + ", proxyPort=" + proxyPort + ", proxyUser=" + proxyUser + "]");

    /////////////////////////////////////////////////////////////////////////////////////////

    //      /////////////////////////////////////////////////////////////////////////////////////////
    //      // fetch request parameters
    //
    //      // unfortunately we must step through the whole set of keys ... 
    //      for(String key : cfg.getOptions().keySet()) {
    //         if(key.startsWith(REQUEST_PARAM_OPTION_PREFIX)) {
    //            String value = (String)cfg.getOption(key);
    //            String requestParameterName = key.substring(REQUEST_PARAM_OPTION_PREFIX.length(), key.length());            
    //            httpParameters.setParameter(requestParameterName, value);            
    //            if(logger.isDebugEnabled())
    //               logger.debug("activity[name="+getName()+", id="+getId()+", requestParameter="+requestParameterName+", value="+value+"]");
    //         }
    //      }
    //
    //      /////////////////////////////////////////////////////////////////////////////////////////

    /////////////////////////////////////////////////////////////////////////////////////////
    // configure scheme registry and initialize http client

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

    if (logger.isDebugEnabled())
        logger.debug("activity[name=" + getName() + ", id=" + getId() + ", registeredSchemes={http, https}]");

    ThreadSafeClientConnManager threadSafeClientConnectionManager = new ThreadSafeClientConnManager(
            schemeRegistry);
    threadSafeClientConnectionManager.setMaxTotal(maxConnections);
    threadSafeClientConnectionManager.setDefaultMaxPerRoute(maxConnections);
    this.httpClient = new DefaultHttpClient(threadSafeClientConnectionManager);

    if (this.basicAuthUsername != null && !this.basicAuthUsername.trim().isEmpty()
            && this.basicAuthPassword != null && !this.basicAuthPassword.trim().isEmpty()) {
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(this.basicAuthUsername,
                this.basicAuthPassword);
        AuthScope authScope = null;
        if (basicAuthHostScope != null && !basicAuthHostScope.isEmpty() && basicAuthPortScope > 0) {
            authScope = new AuthScope(basicAuthHostScope, basicAuthPortScope);
        } else {
            authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT);
        }

        this.httpClient.getCredentialsProvider().setCredentials(authScope, creds);

        if (logger.isDebugEnabled())
            logger.debug("activity[name=" + getName() + ", id=" + getId() + ", credentials=("
                    + creds.getUserName() + ", " + creds.getPassword() + "), authScope=(" + authScope.getHost()
                    + ":" + authScope.getPort() + ")]");
    }

    if (logger.isDebugEnabled())
        logger.debug("activity[name=" + getName() + ", id=" + getId()
                + ", threadSafeClientConnectionManager=initialized]");

}

From source file:de.ub0r.android.websms.connector.common.Utils.java

/**
 * Get a fresh HTTP-Connection./*from  w w  w.j a  v a2s  .  c  om*/
 * 
 * @param o
 *            {@link HttpOptions}
 * @return the connection
 * @throws IOException
 *             IOException
 */
public static HttpResponse getHttpClient(final HttpOptions o) throws IOException {
    if (verboseLog) {
        Log.d(TAG, "HTTPClient URL: " + o.url);
    } else {
        Log.d(TAG, "HTTPClient URL: " + o.url.replaceFirst("\\?.*", ""));
    }

    if (httpClient == null) {
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", new PlainSocketFactory(), PORT_HTTP));
        SocketFactory httpsSocketFactory;
        if (o.trustAll) {
            httpsSocketFactory = new FakeSocketFactory();
        } else if (o.knownFingerprints != null && o.knownFingerprints.length > 0) {
            httpsSocketFactory = new FakeSocketFactory(o.knownFingerprints);
        } else {
            httpsSocketFactory = SSLSocketFactory.getSocketFactory();
        }
        registry.register(new Scheme("https", httpsSocketFactory, PORT_HTTPS));
        HttpParams params = new BasicHttpParams();

        HttpConnectionParams.setConnectionTimeout(params, o.timeout);
        HttpConnectionParams.setSoTimeout(params, o.timeout);

        if (o.maxConnections > 0) {
            ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRoute() {
                public int getMaxForRoute(final HttpRoute httproute) {
                    return o.maxConnections;
                }
            });
        }

        httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(params, registry), params);

        httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
            public void process(final HttpResponse response, final HttpContext context)
                    throws HttpException, IOException {
                HttpEntity entity = response.getEntity();
                Header contentEncodingHeader = entity.getContentEncoding();
                if (contentEncodingHeader != null) {
                    HeaderElement[] codecs = contentEncodingHeader.getElements();
                    for (HeaderElement codec : codecs) {
                        if (codec.getName().equalsIgnoreCase(GZIP)) {
                            response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                            return;
                        }
                    }
                }
            }
        });
    }
    if (o.cookies != null && o.cookies.size() > 0) {
        final int l = o.cookies.size();
        CookieStore cs = httpClient.getCookieStore();
        for (int i = 0; i < l; i++) {
            cs.addCookie(o.cookies.get(i));
        }
    }
    // . Log.d(TAG, getCookies(httpClient));

    HttpRequestBase request;
    if (o.postData == null) {
        request = new HttpGet(o.url);
    } else {
        HttpPost pr = new HttpPost(o.url);
        pr.setEntity(o.postData);
        // . Log.d(TAG, "HTTPClient POST: " + postData);
        request = pr;
    }
    request.addHeader("Accept", "*/*");
    request.addHeader(ACCEPT_ENCODING, GZIP);

    if (o.referer != null) {
        request.setHeader("Referer", o.referer);
        if (verboseLog) {
            Log.d(TAG, "HTTPClient REF: " + o.referer);
        }
    }

    if (o.userAgent != null) {
        request.setHeader("User-Agent", o.userAgent);
        if (verboseLog) {
            Log.d(TAG, "HTTPClient AGENT: " + o.userAgent);
        }
    }

    addHeaders(request, o.headers);

    if (verboseLog) {
        Log.d(TAG, "HTTP " + request.getMethod() + " " + request.getURI());
        Log.d(TAG, getHeaders(request));
        if (request instanceof HttpPost) {
            Log.d(TAG, "");
            Log.d(TAG, ((HttpPost) request).getEntity().getContent());
        }
    }
    return httpClient.execute(request);
}

From source file:com.github.vseguip.sweet.rest.SugarRestAPI.java

/**
 * Get an HttpConnection object. Will create a new one if needed.
 * /*from   w w w  . j  av  a  2  s  .com*/
 * @return A defualt HTTP connection object
 */
private HttpClient getConnection() {
    if (mHttpClient == null) {
        // registers schemes for both http and https
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
        HttpProtocolParams.setUseExpectContinue(params, false);
        HttpConnectionParams.setConnectionTimeout(params, TIMEOUT_OPS);
        HttpConnectionParams.setSoTimeout(params, TIMEOUT_OPS);
        ConnManagerParams.setTimeout(params, TIMEOUT_OPS);
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        final SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
        sslSocketFactory.setHostnameVerifier(SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        if (!mNoCertValidation)
            registry.register(new Scheme("https", sslSocketFactory, 443));
        else
            registry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
        ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params, registry);
        mHttpClient = new DefaultHttpClient(manager, params);

    }
    return mHttpClient;
}

From source file:com.mike.aframe.http.KJHttp.java

/**
 * ?httpClient//from  w  w w  .j  av a  2  s.c  o m
 */
private void initHttpClient() {
    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, config.getConnectTimeOut());
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(config.getMaxConnections()));
    ConnManagerParams.setMaxTotalConnections(httpParams, config.getMaxConnections());

    HttpConnectionParams.setSoTimeout(httpParams, config.getConnectTimeOut());
    HttpConnectionParams.setConnectionTimeout(httpParams, config.getConnectTimeOut());
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, config.getSocketBuffer());

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

    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("Accept-Encoding")) {
                request.addHeader("Accept-Encoding", "gzip");
            }

            for (Entry<String, String> entry : config.getHeader().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("gzip")) {
                        response.setEntity(new InflatingEntity(response.getEntity()));
                        break;
                    }
                }
            }
        }
    });
    threadPool = (ThreadPoolExecutor) KJThreadExecutors.newCachedThreadPool();
    httpClient.setHttpRequestRetryHandler(new RetryHandler(config.getReadTimeout()));
    requestMap = new WeakHashMap<Context, List<WeakReference<Future<?>>>>();
}

From source file:com.cssn.samplesdk.ShowDataActivity.java

private JSONObject sendJsonRequest(int port, String uri, JSONObject param)
        throws ClientProtocolException, IOException, JSONException {
    //HttpClient httpClient = new DefaultHttpClient();
    DefaultHttpClient client = new DefaultHttpClient();
    X509HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    SchemeRegistry registry = new SchemeRegistry();

    SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
    socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
    registry.register(new Scheme("https", socketFactory, 443));
    SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
    DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());

    // Set verifier
    HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

    HttpPost httpPost = new HttpPost(uri);
    httpPost.addHeader("Content-Type", "application/json; charset=utf-8");
    httpPost.addHeader("dataType", "json");

    if (param != null) {
        HttpEntity bodyEntity = new StringEntity(param.toString(), "utf8");
        httpPost.setEntity(bodyEntity);/*w w w. ja  v a 2s.  c o  m*/
    }

    try {
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();

        String result = null;
        if (entity != null) {
            InputStream instream = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
            StringBuilder sb = new StringBuilder();

            String line = null;
            while ((line = reader.readLine()) != null)
                sb.append(line + "\n");

            result = sb.toString();
            instream.close();
        }

        httpPost.abort();
        return result != null ? new JSONObject(result) : null;
    } catch (Exception e1) {
        e1.printStackTrace();
        return null;
    }

}

From source file:com.googlecode.sardine.impl.SardineImpl.java

/**
 * @return Default SSL socket factory
 */
protected SSLSocketFactory createDefaultSecureSocketFactory() {
    return SSLSocketFactory.getSocketFactory();
}

From source file:com.tgx.tina.android.plugin.downloader.DownloadThread.java

private DefaultHttpClient newHttpClient(String userAgent) {
    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, 20 * 1000);
    HttpConnectionParams.setSoTimeout(params, 20 * 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.
    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 conman = new ThreadSafeClientConnManager(params, schemeRegistry);

    return new DefaultHttpClient(conman, params);
}

From source file:org.apache.axis2.transport.http.impl.httpclient4.HTTPSenderImpl.java

protected AbstractHttpClient getHttpClient(MessageContext msgContext) {
    ConfigurationContext configContext = msgContext.getConfigurationContext();

    AbstractHttpClient httpClient = (AbstractHttpClient) msgContext
            .getProperty(HTTPConstants.CACHED_HTTP_CLIENT);

    if (httpClient == null) {
        httpClient = (AbstractHttpClient) configContext.getProperty(HTTPConstants.CACHED_HTTP_CLIENT);
    }//from  w  w w .  j a  v a2s.co  m

    if (httpClient != null) {
        return httpClient;
    }

    synchronized (this) {
        httpClient = (AbstractHttpClient) msgContext.getProperty(HTTPConstants.CACHED_HTTP_CLIENT);

        if (httpClient == null) {
            httpClient = (AbstractHttpClient) configContext.getProperty(HTTPConstants.CACHED_HTTP_CLIENT);
        }

        if (httpClient != null) {
            return httpClient;
        }

        ClientConnectionManager connManager = (ClientConnectionManager) msgContext
                .getProperty(HTTPConstants.MULTITHREAD_HTTP_CONNECTION_MANAGER);
        if (connManager == null) {
            connManager = (ClientConnectionManager) msgContext
                    .getProperty(HTTPConstants.MULTITHREAD_HTTP_CONNECTION_MANAGER);
        }
        if (connManager == null) {
            // reuse HttpConnectionManager
            synchronized (configContext) {
                connManager = (ClientConnectionManager) configContext
                        .getProperty(HTTPConstants.MULTITHREAD_HTTP_CONNECTION_MANAGER);
                if (connManager == null) {
                    log.trace("Making new ConnectionManager");
                    SchemeRegistry schemeRegistry = new SchemeRegistry();
                    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
                    schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

                    connManager = new PoolingClientConnectionManager(schemeRegistry);
                    ((PoolingClientConnectionManager) connManager).setMaxTotal(200);
                    ((PoolingClientConnectionManager) connManager).setDefaultMaxPerRoute(200);
                    configContext.setProperty(HTTPConstants.MULTITHREAD_HTTP_CONNECTION_MANAGER, connManager);
                }
            }
        }
        /*
         * Create a new instance of HttpClient since the way it is used here
         * it's not fully thread-safe.
         */
        HttpParams clientParams = new BasicHttpParams();
        clientParams.setParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET, "UTF-8");
        httpClient = new DefaultHttpClient(connManager, clientParams);

        //We don't need to set timeout for connection manager, since we are doing it below
        // and its enough

        // Get the timeout values set in the runtime
        initializeTimeouts(msgContext, httpClient);

        return httpClient;
    }
}

From source file:com.benefit.buy.library.http.query.callback.AbstractAjaxCallback.java

private static DefaultHttpClient getClient() {
    if ((client == null) || !REUSE_CLIENT) {
        AQUtility.debug("creating http client");
        HttpParams httpParams = new BasicHttpParams();
        //httpParams.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        HttpConnectionParams.setConnectionTimeout(httpParams, NET_TIMEOUT);
        HttpConnectionParams.setSoTimeout(httpParams, NET_TIMEOUT);
        //ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(NETWORK_POOL));
        ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(25));
        //Added this line to avoid issue at: http://stackoverflow.com/questions/5358014/android-httpclient-oom-on-4g-lte-htc-thunderbolt
        HttpConnectionParams.setSocketBufferSize(httpParams, 8192);
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", ssf == null ? SSLSocketFactory.getSocketFactory() : ssf, 443));
        ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, registry);
        client = new DefaultHttpClient(cm, httpParams);
    }//from  ww  w  .  j  a  v  a  2s  .c  om
    return client;
}