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

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

Introduction

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

Prototype

public void setHostnameVerifier(final X509HostnameVerifier hostnameVerifier) 

Source Link

Usage

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);//  ww  w.  ja  v a2  s .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:org.wso2.automation.platform.tests.apim.is.SingleSignOnTestCase.java

@BeforeClass(alwaysRun = true)
public void init() throws APIManagerIntegrationTestException {

    super.init(TestUserMode.SUPER_TENANT_ADMIN);
    HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

    DefaultHttpClient client = new DefaultHttpClient();

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

    httpClient = new DefaultHttpClient(mgr, client.getParams());

    CookieStore cookieStore = new BasicCookieStore();

    // Set verifier
    HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

    AutomationContext isContext;//from  w  w  w . j  a  v a  2 s  . c  o m
    httpsPublisherUrl = publisherUrls.getWebAppURLHttps() + "publisher";
    httpsStoreUrl = storeUrls.getWebAppURLHttps() + "store";
    try {
        providerName = publisherContext.getContextTenant().getContextUser().getUserName();
    } catch (XPathExpressionException e) {
        log.error(e);
        throw new APIManagerIntegrationTestException("Error while getting server url", e);
    }

    try {
        isContext = new AutomationContext("IS", "SP", TestUserMode.SUPER_TENANT_ADMIN);
        commonAuthUrl = isContext.getContextUrls().getBackEndUrl().replaceAll("services/", "") + "commonauth";
        samlSsoEndpointUrl = isContext.getContextUrls().getBackEndUrl().replaceAll("services/", "") + "samlsso";
    } catch (XPathExpressionException e) {
        log.error("Error initializing IS server details", e);
        throw new APIManagerIntegrationTestException("Error initializing IS server details", e);
    }

}

From source file:de.wikilab.android.friendica01.TwAjax.java

public DefaultHttpClient getNewHttpClient() {
    if (ignoreSSLCerts) {
        try {/*w w w . j av a2  s.  com*/
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);

            SSLSocketFactory sf = new IgnoreCertsSSLSocketFactory(trustStore);
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

            HttpParams params = new BasicHttpParams();
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

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

            ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

            return new DefaultHttpClient(ccm, params);
        } catch (Exception e) {
            return new DefaultHttpClient();
        }
    } else {
        return new DefaultHttpClient();
    }
}

From source file:de.geomobile.joined.api.service.JOWebService.java

/**
 * @return/*from  w  ww . ja  v a2s .  c o  m*/
 */
private HttpClient getNewHttpClient() {
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new JOSSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, 10000);
        HttpConnectionParams.setSoTimeout(params, 10000);
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

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

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:com.heaptrip.util.http.bixo.fetcher.SimpleHttpFetcher.java

private synchronized void init() {
    if (_httpClient == null) {
        // Create and initialize HTTP parameters
        HttpParams params = new BasicHttpParams();

        // TODO KKr - w/4.1, switch to new api (ThreadSafeClientConnManager)
        // cm.setMaxTotalConnections(_maxThreads);
        // cm.setDefaultMaxPerRoute(Math.max(10, _maxThreads/10));
        ConnManagerParams.setMaxTotalConnections(params, _maxThreads);

        // Set the maximum time we'll wait for a spare connection in the
        // connection pool. We
        // shouldn't actually hit this, as we make sure (in FetcherManager) that
        // the max number
        // of active requests doesn't exceed the value returned by getMaxThreads()
        // here.// w  w  w  .ja  v a  2 s  .  c o m
        ConnManagerParams.setTimeout(params, CONNECTION_POOL_TIMEOUT);

        // Set the socket and connection timeout to be something reasonable.
        HttpConnectionParams.setSoTimeout(params, _socketTimeout);
        HttpConnectionParams.setConnectionTimeout(params, _connectionTimeout);

        // Even with stale checking enabled, a connection can "go stale" between
        // the check and the
        // next request. So we still need to handle the case of a closed socket
        // (from the server side),
        // and disabling this check improves performance.
        HttpConnectionParams.setStaleCheckingEnabled(params, false);

        // FUTURE - set this on a per-route (host) basis when we have per-host
        // policies for
        // doing partner crawls. We could define a BixoConnPerRoute class that
        // supports this.
        ConnPerRouteBean connPerRoute = new ConnPerRouteBean(_fetcherPolicy.getMaxConnectionsPerHost());
        ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);

        HttpProtocolParams.setVersion(params, _httpVersion);
        HttpProtocolParams.setUserAgent(params, _userAgent.getUserAgentString());
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        HttpProtocolParams.setHttpElementCharset(params, "UTF-8");
        HttpProtocolParams.setUseExpectContinue(params, true);

        // TODO KKr - set on connection manager params, or client params?
        CookieSpecParamBean cookieParams = new CookieSpecParamBean(params);
        cookieParams.setSingleHeader(true);

        // Create and initialize scheme registry
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        SSLSocketFactory sf = null;

        if (sf != null) {
            sf.setHostnameVerifier(new DummyX509HostnameVerifier());
            schemeRegistry.register(new Scheme("https", sf, 443));
        } else {
            LOGGER.warn("No valid SSLContext found for https");
        }

        // Use ThreadSafeClientConnManager since more than one thread will be
        // using the HttpClient.
        ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
        _httpClient = new DefaultHttpClient(cm, params);
        _httpClient.setHttpRequestRetryHandler(new MyRequestRetryHandler(_maxRetryCount));
        _httpClient.setRedirectHandler(new MyRedirectHandler(_fetcherPolicy.getRedirectMode()));
        _httpClient.addRequestInterceptor(new MyRequestInterceptor());

        params = _httpClient.getParams();
        // FUTURE KKr - support authentication
        HttpClientParams.setAuthenticating(params, false);
        HttpClientParams.setCookiePolicy(params, CookiePolicy.BEST_MATCH);

        ClientParamBean clientParams = new ClientParamBean(params);
        if (_fetcherPolicy.getMaxRedirects() == 0) {
            clientParams.setHandleRedirects(false);
        } else {
            clientParams.setHandleRedirects(true);
            clientParams.setMaxRedirects(_fetcherPolicy.getMaxRedirects());
        }

        // Set up default headers. This helps us get back from servers what we
        // want.
        HashSet<Header> defaultHeaders = new HashSet<Header>();
        defaultHeaders
                .add(new BasicHeader(HttpHeaderNames.ACCEPT_LANGUAGE, _fetcherPolicy.getAcceptLanguage()));
        defaultHeaders.add(new BasicHeader(HttpHeaderNames.ACCEPT_CHARSET, DEFAULT_ACCEPT_CHARSET));
        defaultHeaders.add(new BasicHeader(HttpHeaderNames.ACCEPT, DEFAULT_ACCEPT));

        clientParams.setDefaultHeaders(defaultHeaders);
    }
}

From source file:de.mendelson.comm.as2.send.MessageHttpUploader.java

private Scheme createHTTPSScheme() throws Exception {
    //cert store not set so far: take the preferences data
    if (this.certStore == null) {
        this.certStore = new KeystoreStorageImplFile(this.preferences.get(PreferencesAS2.KEYSTORE_HTTPS_SEND),
                this.preferences.get(PreferencesAS2.KEYSTORE_HTTPS_SEND_PASS).toCharArray(),
                BCCryptoHelper.KEYSTORE_JKS);
        this.trustStore = new KeystoreStorageImplFile(this.preferences.get(PreferencesAS2.KEYSTORE_HTTPS_SEND),
                this.preferences.get(PreferencesAS2.KEYSTORE_HTTPS_SEND_PASS).toCharArray(),
                BCCryptoHelper.KEYSTORE_JKS);
    }/*from  w  ww .  j a  v  a 2s . c om*/
    SSLSocketFactory socketFactory = new SSLSocketFactory(this.certStore.getKeystore(),
            new String(this.certStore.getKeystorePass()), this.trustStore.getKeystore());
    socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    return (new Scheme("https", socketFactory, 443));
}

From source file:org.cloudifysource.restclient.GSRestClient.java

/**
 * Returns a HTTP client configured to use SSL.
 *
 * @return HTTP client configured to use SSL
 * @throws RestException/* w  w  w.jav  a 2  s.c  o  m*/
 *             Reporting different failures while creating the HTTP client
 */
public final DefaultHttpClient getSSLHttpClient() throws RestException {
    try {
        final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        // TODO : support self-signed certs if configured by user upon
        // "connect"
        trustStore.load(null, null);

        final SSLSocketFactory sf = new RestSSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        final HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        final SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme(HTTPS, sf, url.getPort()));

        final ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        return new DefaultHttpClient(ccm, params);
    } catch (final KeyStoreException e) {
        throw new RestException(e);
    } catch (final NoSuchAlgorithmException e) {
        throw new RestException(e);
    } catch (final CertificateException e) {
        throw new RestException(e);
    } catch (final IOException e) {
        throw new RestException(e);
    } catch (final KeyManagementException e) {
        throw new RestException(e);
    } catch (final UnrecoverableKeyException e) {
        throw new RestException(e);
    }
}

From source file:edu.isi.misd.tagfiler.client.JakartaClient.java

/**
 * Initialize the HTTP client/*from ww  w.j  a v a2s  . c  om*/
 * 
 * @param connections
 *            the maximum number of HTTP connections
 * @param socketBufferSize
 *            the socket buffer size
 * @param socketTimeout
 *            the socket buffer timeout
 */
private void init(int maxConnections, int socketBufferSize, int socketTimeout) throws Throwable {
    TrustManager easyTrustManager = new X509TrustManager() {

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // Oh, I am easy!
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            if (chain != null) {
                for (int i = 0; i < chain.length; i++) {
                    chain[i].checkValidity();
                }
            }
        }

        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

    };

    SSLContext sslcontext = SSLContext.getInstance("SSL");
    sslcontext.init(null, new TrustManager[] { easyTrustManager }, null);
    SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    BasicHttpParams params = new BasicHttpParams();
    params.setParameter("http.protocol.handle-redirects", false);
    params.setParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, socketBufferSize);
    params.setParameter(CoreConnectionPNames.SO_TIMEOUT, socketTimeout);

    // enable parallelism
    ConnPerRouteBean connPerRoute = new ConnPerRouteBean(maxConnections);
    ConnManagerParams.setMaxTotalConnections(params, maxConnections >= 2 ? maxConnections : 2);
    ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    Scheme sch = new Scheme("https", sf, 443);
    schemeRegistry.register(sch);
    //schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);

    httpclient = new DefaultHttpClient(cm, params);
    BasicCookieStore cookieStore = new BasicCookieStore();
    httpclient.setCookieStore(cookieStore);
}