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.swater.meimeng.activity.oomimg.ImageCache.java

/**
 * Gets an instance of AndroidHttpClient if the devices has it (it was introduced in 2.2), or
 * falls back on a http client that should work reasonably well.
 *
 * @return a working instance of an HttpClient
 *///from   w ww . ja  va2  s.  c  o m
private HttpClient getHttpClient() {
    HttpClient ahc;
    try {
        final Class<?> ahcClass = Class.forName("android.net.http.AndroidHttpClient");
        final Method newInstance = ahcClass.getMethod("newInstance", String.class);
        ahc = (HttpClient) newInstance.invoke(null, "ImageCache");

    } catch (final ClassNotFoundException e) {
        DefaultHttpClient dhc = new DefaultHttpClient();
        final HttpParams params = dhc.getParams();
        dhc = null;

        params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20 * 1000);

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

        final ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params, registry);
        ahc = new DefaultHttpClient(manager, params);

    } catch (final NoSuchMethodException e) {

        final RuntimeException re = new RuntimeException("Programming error");
        re.initCause(e);
        throw re;

    } catch (final IllegalAccessException e) {
        final RuntimeException re = new RuntimeException("Programming error");
        re.initCause(e);
        throw re;

    } catch (final InvocationTargetException e) {
        final RuntimeException re = new RuntimeException("Programming error");
        re.initCause(e);
        throw re;
    }
    return ahc;
}

From source file:com.yibu.kuaibu.app.glApplication.java

private HttpClient createHttpClient() {
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
    HttpProtocolParams.setUseExpectContinue(params, true);
    HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);
    HttpConnectionParams.setSoTimeout(params, 20 * 1000);
    HttpConnectionParams.setSocketBufferSize(params, 8192);
    SchemeRegistry schReg = new SchemeRegistry();
    schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

    ClientConnectionManager connMgr = new ThreadSafeClientConnManager(params, schReg);

    return new DefaultHttpClient(connMgr, params);
}

From source file:com.corebase.android.framework.http.client.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient./*from   w ww . j av  a 2 s. c om*/
 * 
 * @throws KeyStoreException
 */
private AsyncHttpClient() {
    //      CustomSSLSocketFactory customSSLSocketFactory = null;
    //      try {
    //         customSSLSocketFactory = initCustomSSLSocketFactory();
    //      } catch (Exception e) {
    //         e.printStackTrace();
    //      }
    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));
    // schemeRegistry.register(new Scheme("https", customSSLSocketFactory !=
    // null ? customSSLSocketFactory : SSLSocketFactory.getSocketFactory(),
    // 443));
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);
    httpClient = new DefaultHttpClient(cm, httpParams);

    httpClient.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
    /*
     * if(Proxy.getAddress()!=null){//?? HttpHost proxyHost = new
     * HttpHost(Proxy.getAddress().getHost(),Proxy.getAddress().getPort());
     * httpClient
     * .getParams().setParameter(ConnRouteParams.DEFAULT_PROXY,proxyHost); }
     */

    init();

    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            if (!request.containsHeader(USER_AGENT)) {
                if (null != USER_AGENT && !"".equals(USER_AGENT)) {
                    request.addHeader("User-Agent", USER_AGENT);
                }
            }

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

    /**
     * ??????
     * ????? execute
     * ????  60
     * ? ???
     */
    // threadPool = (ThreadPoolExecutor)Executors.newCachedThreadPool();

    /**
     * ??????  nThreads
     * ?????
     * ???
     * ?? ???
     */
    // threadPool = (ThreadPoolExecutor)Executors.newFixedThreadPool(3);

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

From source file:com.funambol.platform.HttpConnectionAdapter.java

public HttpConnectionAdapter() {

    // These default values are mostly grabbed from the AndroidDefaultClient
    // implementation that was introduced in Android 2.2
    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    params.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, HTTP.UTF_8);
    params.setParameter(CoreProtocolPNames.USER_AGENT, "Apache-HttpClient/Android");
    HttpConnectionParams.setConnectionTimeout(params, SOCKET_OPERATION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, SOCKET_OPERATION_TIMEOUT);
    // 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.
    params.setParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false);
    //HttpConnectionParams.setSocketBufferSize(params, 8192);

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

From source file:org.switchyard.component.resteasy.util.ClientInvoker.java

/**
 * Create a RESTEasy invoker client./*from ww w  .  j av a  2s  . c  o m*/
 *
 * @param basePath The base path for the class
 * @param resourceClass The JAX-RS Resource Class
 * @param method The JAX-RS Resource Class's method
 * @param model Configuration model
 */
public ClientInvoker(String basePath, Class<?> resourceClass, Method method, RESTEasyBindingModel model) {
    Set<String> httpMethods = IsHttpMethod.getHttpMethods(method);
    _baseUri = createUri(basePath);
    if ((httpMethods == null || httpMethods.size() == 0) && method.isAnnotationPresent(Path.class)
            && method.getReturnType().isInterface()) {
        _subResourcePath = createSubResourcePath(basePath, method);
    } else if (httpMethods == null || httpMethods.size() != 1) {
        throw RestEasyMessages.MESSAGES
                .youMustUseAtLeastOneButNoMoreThanOneHttpMethodAnnotationOn(method.toString());
    }
    _httpMethod = httpMethods.iterator().next();
    _resourceClass = resourceClass;
    _method = method;
    try {
        _uri = (UriBuilder) URIBUILDER_CLASS.newInstance();
    } catch (InstantiationException ie) {
        throw new RuntimeException(ie);
    } catch (IllegalAccessException iae) {
        throw new RuntimeException(iae);
    }
    _uri.uri(_baseUri);
    if (_resourceClass.isAnnotationPresent(Path.class)) {
        _uri.path(_resourceClass);
    }
    if (_method.isAnnotationPresent(Path.class)) {
        _uri.path(_method);
    }

    _providerFactory = new ResteasyProviderFactory();

    boolean useBuiltins = true; // use builtin @Provider classes by default
    if (model.getContextParamsConfig() != null) {
        Map<String, String> contextParams = model.getContextParamsConfig().toMap();

        // Set use builtin @Provider classes
        String registerBuiltins = contextParams.get(ResteasyContextParameters.RESTEASY_USE_BUILTIN_PROVIDERS);
        if (registerBuiltins != null) {
            useBuiltins = Boolean.parseBoolean(registerBuiltins);
        }

        // Register @Provider classes
        List<Class<?>> providerClasses = RESTEasyUtil.getProviderClasses(contextParams);
        if (providerClasses != null) {
            for (Class<?> pc : providerClasses) {
                _providerFactory.registerProvider(pc);
            }
        }

        List<ClientErrorInterceptor> interceptors = RESTEasyUtil.getClientErrorInterceptors(contextParams);
        if (interceptors != null) {
            for (ClientErrorInterceptor interceptor : interceptors) {
                _providerFactory.addClientErrorInterceptor(interceptor);
            }
        }
    }
    if (useBuiltins) {
        _providerFactory.setRegisterBuiltins(true);
        RegisterBuiltin.register(_providerFactory);
    }

    _extractorFactory = new DefaultEntityExtractorFactory();
    _extractor = _extractorFactory.createExtractor(_method);
    _marshallers = ClientMarshallerFactory.createMarshallers(_resourceClass, _method, _providerFactory, null);
    _accepts = MediaTypeHelper.getProduces(_resourceClass, method, null);
    ClientInvokerInterceptorFactory.applyDefaultInterceptors(this, _providerFactory, _resourceClass, _method);

    // Client executor
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    int port = _baseUri.getPort();
    if (_baseUri.getScheme().startsWith("https")) {
        if (port == -1) {
            port = 443;
        }
        SSLSocketFactory sslFactory = getSSLSocketFactory(model.getSSLContextConfig());
        if (sslFactory == null) {
            sslFactory = SSLSocketFactory.getSocketFactory();
        }
        schemeRegistry.register(new Scheme(_baseUri.getScheme(), port, sslFactory));
    } else {
        if (port == -1) {
            port = 80;
        }
        schemeRegistry.register(new Scheme(_baseUri.getScheme(), port, PlainSocketFactory.getSocketFactory()));
    }
    PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
    cm.setMaxTotal(200);
    cm.setDefaultMaxPerRoute(20);
    HttpClient httpClient = new DefaultHttpClient(cm);
    _executor = new ApacheHttpClient4Executor(httpClient);
    // register ApacheHttpClient4ExceptionMapper manually for local instance of ResteasyProviderFactory
    Type exceptionType = Types.getActualTypeArgumentsOfAnInterface(ApacheHttpClient4ExceptionMapper.class,
            ClientExceptionMapper.class)[0];
    _providerFactory.addClientExceptionMapper(new ApacheHttpClient4ExceptionMapper(), exceptionType);

    // Authentication settings
    if (model.hasAuthentication()) {
        // Set authentication
        AuthScope authScope = null;
        Credentials credentials = null;
        if (model.isBasicAuth()) {
            authScope = createAuthScope(model.getBasicAuthConfig().getHost(),
                    model.getBasicAuthConfig().getPort(), model.getBasicAuthConfig().getRealm());
            credentials = new UsernamePasswordCredentials(model.getBasicAuthConfig().getUser(),
                    model.getBasicAuthConfig().getPassword());
            // Create AuthCache instance
            AuthCache authCache = new BasicAuthCache();
            authCache.put(new HttpHost(authScope.getHost(), authScope.getPort()),
                    new BasicScheme(ChallengeState.TARGET));
            BasicHttpContext context = new BasicHttpContext();
            context.setAttribute(ClientContext.AUTH_CACHE, authCache);
            ((ApacheHttpClient4Executor) _executor).setHttpContext(context);
        } else {
            authScope = createAuthScope(model.getNtlmAuthConfig().getHost(),
                    model.getNtlmAuthConfig().getPort(), model.getNtlmAuthConfig().getRealm());
            credentials = new NTCredentials(model.getNtlmAuthConfig().getUser(),
                    model.getNtlmAuthConfig().getPassword(), "", model.getNtlmAuthConfig().getDomain());
        }
        ((DefaultHttpClient) httpClient).getCredentialsProvider().setCredentials(authScope, credentials);
    } else {
        ProxyModel proxy = model.getProxyConfig();
        if (proxy != null) {
            HttpHost proxyHost = null;
            if (proxy.getPort() != null) {
                proxyHost = new HttpHost(proxy.getHost(), Integer.valueOf(proxy.getPort()).intValue());
            } else {
                proxyHost = new HttpHost(proxy.getHost(), -1);
            }
            if (proxy.getUser() != null) {
                AuthScope authScope = new AuthScope(proxy.getHost(),
                        Integer.valueOf(proxy.getPort()).intValue(), AuthScope.ANY_REALM);
                Credentials credentials = new UsernamePasswordCredentials(proxy.getUser(), proxy.getPassword());
                AuthCache authCache = new BasicAuthCache();
                authCache.put(proxyHost, new BasicScheme(ChallengeState.PROXY));
                ((DefaultHttpClient) httpClient).getCredentialsProvider().setCredentials(authScope,
                        credentials);
                BasicHttpContext context = new BasicHttpContext();
                context.setAttribute(ClientContext.AUTH_CACHE, authCache);
                ((ApacheHttpClient4Executor) _executor).setHttpContext(context);
            }
            httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost);
        }
    }
    Integer timeout = model.getTimeout();
    if (timeout != null) {
        HttpParams httpParams = httpClient.getParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
        HttpConnectionParams.setSoTimeout(httpParams, timeout);
    }
}

From source file:org.sdr.webrec.core.WebRec.java

private void initParameters() {

    // initialize HTTP parameters
    params = new BasicHttpParams();
    ConnManagerParams.setMaxTotalConnections(params, 100);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

    httpclient = new DefaultHttpClient(cm, params);

    //TODO: CloseableHttpClient httpclient = HttpClients.createDefault();

    //set proxy if available in settings
    if (settings.getProxyHost() != null && settings.getProxyHost().length() > 0) {
        HttpHost proxy = new HttpHost(settings.getProxyHost(), settings.getProxyPort());
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

        //set authentication to proxy is available is settings
        if (settings.getProxyUserName() != null && settings.getProxyUserName().length() > 0
                && settings.getProxyPasswd() != null) {
            httpclient.getCredentialsProvider().setCredentials(
                    new AuthScope(settings.getProxyHost(), settings.getProxyPort()),
                    new UsernamePasswordCredentials(settings.getProxyUserName(), settings.getProxyPasswd()));
            LOGGER.debug("autentication for proxy on");
        }/*from  ww w  . ja v  a2s .  co  m*/

    }

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

    // Create an HttpClient with the ThreadSafeClientConnManager.
    // This connection manager must be used if more than one thread will
    // be using the HttpClient.
    cm = new ThreadSafeClientConnManager(params, schemeRegistry);

    httpclient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {

        public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
            // Honor 'keep-alive' header
            HeaderElementIterator it = new BasicHeaderElementIterator(
                    response.headerIterator(HTTP.CONN_KEEP_ALIVE));
            while (it.hasNext()) {
                HeaderElement he = it.nextElement();
                String param = he.getName();
                String value = he.getValue();
                if (value != null && param.equalsIgnoreCase("timeout")) {
                    try {
                        return Long.parseLong(value);
                    } catch (NumberFormatException ignore) {

                    }
                }
            }
            //otherwise keep alive for 30 seconds
            return 30 * 1000;
        }

    });

    httpget = null;

    httpclient = new DefaultHttpClient(cm, params);

    // Create global request configuration
    RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH)
            .setExpectContinueEnabled(true).setStaleConnectionCheckEnabled(settings.isKeepConnectionAlive())
            .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
            .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();

    requestConfig = RequestConfig.copy(defaultRequestConfig).setSocketTimeout(timeout)
            .setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).build();

}

From source file:com.wareninja.android.commonutils.foursquareV2.http.AbstractHttpApi.java

/**
 * Create a thread-safe client. This client does not do redirecting, to allow us to capture
 * correct "error" codes.// www.  j  a va2 s .co  m
 *
 * @return HttpClient
 */
public static final DefaultHttpClient createHttpClient() {
    // Sets up the http part of the service.
    final SchemeRegistry supportedSchemes = new SchemeRegistry();

    // Register the "http" protocol scheme, it is required
    // by the default operator to look up socket factories.
    final SocketFactory sf = PlainSocketFactory.getSocketFactory();
    supportedSchemes.register(new Scheme("http", sf, 80));
    supportedSchemes.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

    // Set some client http client parameter defaults.
    final HttpParams httpParams = createHttpParams();
    HttpClientParams.setRedirecting(httpParams, false);

    final ClientConnectionManager ccm = new ThreadSafeClientConnManager(httpParams, supportedSchemes);
    return new DefaultHttpClient(ccm, httpParams);
}

From source file:com.neusou.bioroid.restful.RestfulClient.java

/**
 * Creates a <b>RestfulClient</b><br/><br/>
 * The intent actions will generated with the following rule: <br/><br/>
 * &lt;the package name of the supplied context&gt;.&lt;the supplied name&gt;.restful.&lt;the action name&gt;
 * /* w  ww. ja v a  2 s  .co m*/
 * <br/><br/>Example: with context has package name com.neusou.facegraph and FB as the restful client name:<br/><br/>
 * com.neusou.facegraph.FB.restful.PROCESS_RESPONSE<br/>
 * com.neusou.facegraph.FB.restful.EXECUTE_REQUEST<br/>
 * com.neusou.facegraph.FB.restful.EXECUTE_REQUEST
 * <br/>
 * @param context context
 * @param name the unique name of the restful client
 */
public RestfulClient(Context context, String name) {
    if (name == null) {
        throw new IllegalArgumentException("name can not be null");
    }

    if (context == null) {
        Logger.l(Logger.WARN, LOG_TAG, "Required Context argument is null.");
    }

    mContext = context;
    mName = name;

    HttpParams httpParams = new BasicHttpParams();
    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParams, "UTF-8");
    httpParams.setBooleanParameter("http.protocol.expect-continue", false);

    SchemeRegistry scheme = new SchemeRegistry();
    scheme.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    final SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
    sslSocketFactory.setHostnameVerifier(SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    scheme.register(new Scheme("https", sslSocketFactory, 443));

    ThreadSafeClientConnManager tscm = new ThreadSafeClientConnManager(httpParams, scheme);

    httpClient = new DefaultHttpClient(tscm, httpParams);
    httpClient.setReuseStrategy(new ConnectionReuseStrategy() {
        @Override
        public boolean keepAlive(HttpResponse response, HttpContext context) {
            return false;
        }
    });

    mExecutor.setRejectedExecutionHandler(new RejectedExecutionHandler() {
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            //   Logger.l(Logger.DEBUG, LOG_TAG, "rejectedExecution. #activethread:"+executor.getActiveCount()+", queue.size:"+executor.getQueue().size());            
        }
    });

    if (context != null) {
        setContext(context);
    }
}

From source file:org.ametro.app.ApplicationEx.java

private HttpClient createHttpClient() {
    if (Log.isLoggable(Constants.LOG_TAG_MAIN, Log.DEBUG)) {
        Log.d(Constants.LOG_TAG_MAIN, "Create HTTP client");
    }/* w w w.  j a  va 2s .c  o m*/
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
    HttpProtocolParams.setUseExpectContinue(params, true);
    HttpConnectionParams.setConnectionTimeout(params, HTTP_CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, HTTP_SOCKET_TIMEOUT);

    SchemeRegistry schReg = new SchemeRegistry();
    schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);
    return new DefaultHttpClient(conMgr, params);
}