Search in sources :

Example 1 with SchemeRegistry

use of org.apache.http.conn.scheme.SchemeRegistry in project OpenAttestation by OpenAttestation.

the class ApacheHttpClient method initSchemeRegistryWithPolicy.

/*
    public final void setBaseURL(URL baseURL) {
        this.baseURL = baseURL;
    }
    public final void setKeystore(SimpleKeystore keystore) {
        this.keystore = keystore;
    }    
    public final void setRequireTrustedCertificate(boolean value) {
        requireTrustedCertificate = value;
    }
    public final void setVerifyHostname(boolean value) {
        verifyHostname = value;
    }
    * 
    */
/**
     * Used in Mt Wilson 1.0-RC2
     * 
     * Base URL and other configuration must already be set before calling this
     * method.
     *
     * @param protocol either "http" or "https"
     * @param port such as 80 for http, 443 for https
     * @throws KeyManagementException
     * @throws NoSuchAlgorithmException 
     */
/*
    private SchemeRegistry initSchemeRegistry(String protocol, int port) throws KeyManagementException, NoSuchAlgorithmException {
        SchemeRegistry sr = new SchemeRegistry();
        if( "http".equals(protocol) ) {
            Scheme http = new Scheme("http", port, PlainSocketFactory.getSocketFactory());
            sr.register(http);
        }
        if( "https".equals(protocol) ) {
            X509HostnameVerifier hostnameVerifier; // secure by default (default verifyHostname = true)
            X509TrustManager trustManager; // secure by default, using Java's implementation which verifies the peer and using java's trusted keystore as default if user does not provide a specific keystore
            if( verifyHostname ) {
                hostnameVerifier = SSLSocketFactory.STRICT_HOSTNAME_VERIFIER;
            }
            else { // if( !config.getBoolean("mtwilson.api.ssl.verifyHostname", true) ) {
                hostnameVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
            }
            
            if( requireTrustedCertificate && keystore != null ) {
                trustManager = SslUtil.createX509TrustManagerWithKeystore(keystore);                
            }
            else if( requireTrustedCertificate ) { // config.getBoolean("mtwilson.api.ssl.requireTrustedCertificate", true) ) {
                //String truststore = config.getString("mtwilson.api.keystore", System.getProperty("javax.net.ssl.trustStorePath")); // if null use default java trust store...
                //String truststorePassword = config.getString("mtwilson.api.keystore.password", System.getProperty("javax.net.ssl.trustStorePassword"));
//                String truststore = System.getProperty("javax.net.ssl.trustStorePath");
                String truststore = System.getProperty("javax.net.ssl.trustStore");
                String truststorePassword = System.getProperty("javax.net.ssl.trustStorePassword");
                
                // create a trust manager using only our trusted ssl certificates
                if( truststore == null || truststorePassword == null ) {
                    throw new IllegalArgumentException("Require trusted certificates is enabled but truststore is not configured");
                }
                keystore = new SimpleKeystore(new File(truststore), truststorePassword);
                trustManager = SslUtil.createX509TrustManagerWithKeystore(keystore);
            }
            else {
                // user does not want to ensure certificates are trusted, so use a no-op trust manager
                trustManager = new NopX509TrustManager();
            }
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, new X509TrustManager[] { trustManager }, null); // key manager, trust manager, securerandom
            SSLSocketFactory sf = new SSLSocketFactory(
                sslcontext,
                hostnameVerifier
                );
            Scheme https = new Scheme("https", port, sf); // URl defaults to 443 for https but if user specified a different port we use that instead
            sr.register(https);            
        }        
        return sr;
    }
    */
/**
     * Used in Mt Wilson 1.1
     * 
     * @param protocol
     * @param port
     * @param policy
     * @return
     * @throws KeyManagementException
     * @throws NoSuchAlgorithmException 
     */
private SchemeRegistry initSchemeRegistryWithPolicy(String protocol, int port, ApacheTlsPolicy policy) throws KeyManagementException, NoSuchAlgorithmException {
    SchemeRegistry sr = new SchemeRegistry();
    if ("http".equals(protocol)) {
        Scheme http = new Scheme("http", port, PlainSocketFactory.getSocketFactory());
        sr.register(http);
    }
    if ("https".equals(protocol)) {
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        // key manager, trust manager, securerandom
        sslcontext.init(null, new X509TrustManager[] { policy.getTrustManager() }, null);
        SSLSocketFactory sf = new SSLSocketFactory(sslcontext, policy.getApacheHostnameVerifier());
        // URl defaults to 443 for https but if user specified a different port we use that instead
        Scheme https = new Scheme("https", port, sf);
        sr.register(https);
    }
    return sr;
}
Also used : Scheme(org.apache.http.conn.scheme.Scheme) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) SSLContext(javax.net.ssl.SSLContext) SSLSocketFactory(org.apache.http.conn.ssl.SSLSocketFactory)

Example 2 with SchemeRegistry

use of org.apache.http.conn.scheme.SchemeRegistry in project OpenAttestation by OpenAttestation.

the class SslUtil method getServerCertificates.

public static X509Certificate[] getServerCertificates(URL url) throws NoSuchAlgorithmException, KeyManagementException, IOException {
    if (!"https".equals(url.getProtocol())) {
        throw new IllegalArgumentException("URL scheme must be https");
    }
    int port = url.getPort();
    if (port == -1) {
        port = 443;
    }
    X509HostnameVerifier hostnameVerifier = new NopX509HostnameVerifierApache();
    CertificateStoringX509TrustManager trustManager = new CertificateStoringX509TrustManager();
    SSLContext sslcontext = SSLContext.getInstance("TLS");
    sslcontext.init(null, new X509TrustManager[] { trustManager }, null);
    SSLSocketFactory sf = new SSLSocketFactory(sslcontext, hostnameVerifier);
    Scheme https = new Scheme("https", port, sf);
    SchemeRegistry sr = new SchemeRegistry();
    sr.register(https);
    BasicClientConnectionManager connectionManager = new BasicClientConnectionManager(sr);
    HttpParams httpParams = new BasicHttpParams();
    httpParams.setParameter(ClientPNames.HANDLE_REDIRECTS, false);
    HttpClient httpClient = new DefaultHttpClient(connectionManager, httpParams);
    log.debug("Saving certificates from server URL: {}", url.toExternalForm());
    HttpHead request = new HttpHead(url.toExternalForm());
    HttpResponse response = httpClient.execute(request);
    log.debug("Server status line: {} {} ({})", new String[] { response.getProtocolVersion().getProtocol(), response.getStatusLine().getReasonPhrase(), String.valueOf(response.getStatusLine().getStatusCode()) });
    httpClient.getConnectionManager().shutdown();
    return trustManager.getStoredCertificates();
}
Also used : Scheme(org.apache.http.conn.scheme.Scheme) HttpResponse(org.apache.http.HttpResponse) SSLContext(javax.net.ssl.SSLContext) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpHead(org.apache.http.client.methods.HttpHead) BasicHttpParams(org.apache.http.params.BasicHttpParams) HttpParams(org.apache.http.params.HttpParams) X509HostnameVerifier(org.apache.http.conn.ssl.X509HostnameVerifier) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) BasicClientConnectionManager(org.apache.http.impl.conn.BasicClientConnectionManager) SSLSocketFactory(org.apache.http.conn.ssl.SSLSocketFactory) BasicHttpParams(org.apache.http.params.BasicHttpParams)

Example 3 with SchemeRegistry

use of org.apache.http.conn.scheme.SchemeRegistry in project android_frameworks_base by ParanoidAndroid.

the class FsUtils method getHttpClient.

private static HttpClient getHttpClient() {
    if (sHttpClient == null) {
        HttpParams params = new BasicHttpParams();
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), ForwarderManager.HTTP_PORT));
        schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), ForwarderManager.HTTPS_PORT));
        ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(params, schemeRegistry);
        sHttpClient = new DefaultHttpClient(connectionManager, params);
        HttpConnectionParams.setSoTimeout(sHttpClient.getParams(), HTTP_TIMEOUT_MS);
        HttpConnectionParams.setConnectionTimeout(sHttpClient.getParams(), HTTP_TIMEOUT_MS);
    }
    return sHttpClient;
}
Also used : BasicHttpParams(org.apache.http.params.BasicHttpParams) HttpParams(org.apache.http.params.HttpParams) Scheme(org.apache.http.conn.scheme.Scheme) ThreadSafeClientConnManager(org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) BasicHttpParams(org.apache.http.params.BasicHttpParams) ClientConnectionManager(org.apache.http.conn.ClientConnectionManager) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient)

Example 4 with SchemeRegistry

use of org.apache.http.conn.scheme.SchemeRegistry in project android_frameworks_base by ParanoidAndroid.

the class AndroidHttpClient method newInstance.

/**
     * Create a new HttpClient with reasonable defaults (which you can update).
     *
     * @param userAgent to report in your HTTP requests
     * @param context to use for caching SSL sessions (may be null for no caching)
     * @return AndroidHttpClient for you to use for all your requests.
     */
public static AndroidHttpClient newInstance(String userAgent, Context context) {
    HttpParams params = new BasicHttpParams();
    // Turn off stale checking.  Our connections break all the time anyway,
    // and it's not worth it to pay the penalty of checking every time.
    HttpConnectionParams.setStaleCheckingEnabled(params, false);
    HttpConnectionParams.setConnectionTimeout(params, SOCKET_OPERATION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, SOCKET_OPERATION_TIMEOUT);
    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);
    // Use a session cache for SSL sockets
    SSLSessionCache sessionCache = context == null ? null : new SSLSessionCache(context);
    // 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", SSLCertificateSocketFactory.getHttpSocketFactory(SOCKET_OPERATION_TIMEOUT, sessionCache), 443));
    ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry);
    // parameters without the funny call-a-static-method dance.
    return new AndroidHttpClient(manager, params);
}
Also used : BasicHttpParams(org.apache.http.params.BasicHttpParams) HttpParams(org.apache.http.params.HttpParams) Scheme(org.apache.http.conn.scheme.Scheme) ThreadSafeClientConnManager(org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) SSLSessionCache(android.net.SSLSessionCache) BasicHttpParams(org.apache.http.params.BasicHttpParams) ClientConnectionManager(org.apache.http.conn.ClientConnectionManager)

Example 5 with SchemeRegistry

use of org.apache.http.conn.scheme.SchemeRegistry in project UltimateAndroid by cymcsg.

the class CommonHttpClient method getNewInstance.

// 每次返回同一实例
// public static synchronized HttpClient getInstance(Context mContext){
//
// if(null == singleStance){
// singleStance = getNewInstance(mContext);
// }
// return singleStance ;
// }
// 每次都返回新的HttpClient实例
public static HttpClient getNewInstance(Context mContext) {
    HttpClient newInstance;
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
    HttpProtocolParams.setUseExpectContinue(params, true);
    // 自定义三个timeout参数
    /*
         * 1.set a timeout for the connection manager,it defines how long we
		 * should wait to get a connection out of the connection pool managed by
		 * the connection manager
		 */
    ConnManagerParams.setTimeout(params, 5000);
    /*
         * 2.The second timeout value defines how long we should wait to make a
		 * connection over the network to the server on the other end
		 */
    HttpConnectionParams.setConnectionTimeout(params, TIMEOUT);
    /*
         * 3.we set a socket timeout value to 4 seconds to define how long we
		 * should wait to get data back for our request.
		 */
    HttpConnectionParams.setSoTimeout(params, TIMEOUT_SOCKET);
    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);
    newInstance = new DefaultHttpClient(conMgr, params);
    switch(checkNetworkTypeDeprecated(mContext)) {
        case TYPE_CT_WAP:
            {
                // 通过代理解决中国移动联通GPRS中wap无法访问的问题
                HttpHost proxy = new HttpHost("10.0.0.200", 80, "http");
                newInstance.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
                Logs.v("当前网络类型为cm_cu_wap,设置代理10.0.0.200访问www");
            }
            break;
        case TYPE_CM_CU_WAP:
            {
                // 通过代理解决中国移动联通GPRS中wap无法访问的问题
                HttpHost proxy = new HttpHost("10.0.0.172", 80, "http");
                newInstance.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
                Logs.v("当前网络类型为cm_cu_wap,设置代理10.0.0.172访问www");
            }
            break;
    }
    return newInstance;
}
Also used : BasicHttpParams(org.apache.http.params.BasicHttpParams) HttpParams(org.apache.http.params.HttpParams) Scheme(org.apache.http.conn.scheme.Scheme) ThreadSafeClientConnManager(org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager) HttpHost(org.apache.http.HttpHost) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) BasicHttpParams(org.apache.http.params.BasicHttpParams) ClientConnectionManager(org.apache.http.conn.ClientConnectionManager) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient)

Aggregations

SchemeRegistry (org.apache.http.conn.scheme.SchemeRegistry)91 Scheme (org.apache.http.conn.scheme.Scheme)88 SSLSocketFactory (org.apache.http.conn.ssl.SSLSocketFactory)58 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)50 ClientConnectionManager (org.apache.http.conn.ClientConnectionManager)48 BasicHttpParams (org.apache.http.params.BasicHttpParams)35 HttpParams (org.apache.http.params.HttpParams)33 ThreadSafeClientConnManager (org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager)30 SSLContext (javax.net.ssl.SSLContext)24 IOException (java.io.IOException)22 KeyManagementException (java.security.KeyManagementException)18 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)18 CertificateException (java.security.cert.CertificateException)15 HttpClient (org.apache.http.client.HttpClient)12 BasicClientConnectionManager (org.apache.http.impl.conn.BasicClientConnectionManager)12 PoolingClientConnectionManager (org.apache.http.impl.conn.PoolingClientConnectionManager)12 KeyStoreException (java.security.KeyStoreException)11 UnrecoverableKeyException (java.security.UnrecoverableKeyException)10 X509Certificate (java.security.cert.X509Certificate)10 X509TrustManager (javax.net.ssl.X509TrustManager)9