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

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

Introduction

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

Prototype

X509HostnameVerifier ALLOW_ALL_HOSTNAME_VERIFIER

To view the source code for org.apache.http.conn.ssl SSLSocketFactory ALLOW_ALL_HOSTNAME_VERIFIER.

Click Source Link

Usage

From source file:org.bedework.util.http.BasicHttpClient.java

/** Allow testing of features when we don't have any valid certs.
 *
 * @return socket factory./* w  ww  .j  a  v  a2 s.c om*/
 */
public static SSLSocketFactory getSslSocketFactory() {
    if (!sslDisabled) {
        return SSLSocketFactory.getSocketFactory();
    }

    try {
        final X509Certificate[] _AcceptedIssuers = new X509Certificate[] {};

        final SSLContext ctx = SSLContext.getInstance("TLS");
        final X509TrustManager tm = new X509TrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return _AcceptedIssuers;
            }

            @Override
            public void checkServerTrusted(final X509Certificate[] chain, final String authType)
                    throws CertificateException {
            }

            @Override
            public void checkClientTrusted(final X509Certificate[] chain, final String authType)
                    throws CertificateException {
            }
        };
        ctx.init(null, new TrustManager[] { tm }, new SecureRandom());

        return new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (final Throwable t) {
        throw new RuntimeException(t);
    }
}

From source file:org.opcfoundation.ua.unittests.TestMaxMessageSize.java

void executeTests(String uri, SecurityMode mode, boolean testClient, boolean testServer,
        HttpsSecurityPolicy httpsSecurityPolicy) throws Exception {
    int[] maxMessageSizes = new int[] { 10000, 10000, 1000, 200000, 100000 };
    int[] msgSizes = new int[] { 1, 1024, 10240, 102400, 200000 };
    boolean[] expectedSuccess = new boolean[] { true, true, false, true, false };

    System.out.println();/*from w  ww. j  a v  a2 s .  com*/
    for (int i = 2; i < expectedSuccess.length; i++) {

        // Test client
        try {
            int msgSize = msgSizes[i];
            int maxMessageSize = maxMessageSizes[i];

            this.uri = uri;
            this.keySize = 1024;

            // Create Server
            server = Server.createServerApplication();
            // Add a service to the server - TestStack echo
            server.addServiceHandler(new TestStackService());

            // Add application instance certificate
            KeyPair myServerKeypair = UnitTestKeys.getKeyPair("server", this.keySize);
            KeyPair myServerHttpsKeypair = UnitTestKeys.getKeyPair("https_server", this.keySize);

            server.getApplication().addApplicationInstanceCertificate(myServerKeypair);
            server.getApplication().getHttpsSettings().setKeyPair(myServerHttpsKeypair);
            server.getApplication().getHttpsSettings()
                    .setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            server.getApplication().getHttpsSettings().setCertificateValidator(CertificateValidator.ALLOW_ALL);
            server.getApplication().getHttpsSettings().setHttpsSecurityPolicies(httpsSecurityPolicy);

            // Bind my server to my endpoint. This binds socket to port 6001 as well 
            Endpoint endpointAddress = new Endpoint(uri, mode);
            if (testServer)
                endpointAddress.getEndpointConfiguration().setMaxMessageSize(maxMessageSize);
            server.bind(uri, endpointAddress);

            // Create client
            KeyPair myClientKeys = UnitTestKeys.getKeyPair("client", this.keySize);
            KeyPair myClientHttpsKeys = UnitTestKeys.getKeyPair("https_client", this.keySize);

            Client client = Client.createClientApplication(myClientKeys);
            client.getApplication().getHttpsSettings().setKeyPair(myClientHttpsKeys);
            client.getApplication().getHttpsSettings()
                    .setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            client.getApplication().getHttpsSettings().setCertificateValidator(CertificateValidator.ALLOW_ALL);
            if (testClient)
                client.getEndpointConfiguration().setMaxMessageSize(maxMessageSize);

            secureChannel = client.createSecureChannel(uri, uri, mode, myServerKeypair.certificate);

            executeTest(secureChannel, msgSize, maxMessageSize);
            if (!expectedSuccess[i]) {
                throw new Exception("Expected failure.");
            }
        } catch (ServiceResultException e) {
            if (expectedSuccess[i])
                throw e;
        } finally {
            _tearDown();
        }

    }
}

From source file:org.ovirt.engine.sdk.web.ConnectionsPoolBuilder.java

/**
 * Creates SchemeRegistry/* w  w w .java  2 s.com*/
 *
 * @param url
 * @param port
 *
 * @return {@link SchemeRegistry}
 */
private SchemeRegistry createSchemeRegistry(String url, int port) {
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    String protocol = getProtocol(url);
    SSLSocketFactory sf;

    if (HTTP_PROTOCOL.equals(protocol)) {
        schemeRegistry.register(new Scheme(HTTP_PROTOCOL, port, PlainSocketFactory.getSocketFactory()));
    } else if (HTTPS_PROTOCOL.equals(protocol)) {
        try {
            if (this.noHostVerification) {
                SSLContext sslcontext = SSLContext.getInstance("TLS");
                sslcontext.init(null, new TrustManager[] { noCaTrustManager }, null);
                sf = new SSLSocketFactory(sslcontext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            } else {
                KeyStore truststore = null;
                InputStream in = null;

                if (this.keyStorePath != null) {
                    truststore = KeyStore.getInstance(KeyStore.getDefaultType());
                    try {
                        in = new FileInputStream(this.keyStorePath);
                        truststore.load(in,
                                this.keyStorePassword != null ? this.keyStorePassword.toCharArray() : null);

                    } finally {
                        if (in != null) {
                            in.close();
                        }
                    }
                }
                sf = new SSLSocketFactory(SSLSocketFactory.TLS, null, null, truststore, null, null,
                        SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
            }

            schemeRegistry.register(new Scheme(HTTPS_PROTOCOL, port, sf));

        } catch (NoSuchAlgorithmException e) {
            throw new SocketFactoryException(NO_TLS_ERROR, e);
        } catch (KeyManagementException e) {
            throw new SocketFactoryException(BAD_KEY_ERROR, e);
        } catch (KeyStoreException e) {
            throw new SocketFactoryException(KEY_STORE_ERROR, e);
        } catch (FileNotFoundException e) {
            throw new SocketFactoryException(KEY_STORE_FILE_NOT_FOUND_ERROR, e);
        } catch (CertificateException e) {
            throw new SocketFactoryException(CERTEFICATE_ERROR, e);
        } catch (IOException e) {
            throw new SocketFactoryException(IO_ERROR, e);
        } catch (UnrecoverableKeyException e) {
            throw new SocketFactoryException(UNRECOVERABLE_KEY_ERROR, e);
        }
    } else {
        throw new ProtocolException(BAD_PROTOCOL_ERROR + protocol);
    }

    return schemeRegistry;
}

From source file:org.wso2.carbon.appfactory.jenkins.build.RestBasedJenkinsCIConnector.java

/**
 * Create the HttpContext and disable host verification
 *
 * @return/*from   w w  w  .java2s.c  o m*/
 * @throws AppFactoryException
 */
public HttpContext getHttpContext() throws AppFactoryException {

    HttpContext httpContext = new BasicHttpContext();
    if (this.allowAllHostNameVerifier) {
        SSLContext sslContext;
        try {
            sslContext = SSLContext.getInstance(SSLSocketFactory.TLS);
            sslContext.init(null, null, null);
        } catch (KeyManagementException e) {
            String msg = "Error while initializing ssl context for http client";
            log.error(msg, e);
            throw new AppFactoryException(msg, e);
        } catch (NoSuchAlgorithmException e) {
            String msg = "Error while initializing ssl context for http client";
            log.error(msg, e);
            throw new AppFactoryException(msg, e);
        }
        SSLSocketFactory sf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Scheme sch = new Scheme("https", 443, sf);
        httpClient.getConnectionManager().getSchemeRegistry().register(sch);
    }
    return httpContext;
}

From source file:com.itude.mobile.mobbl.core.services.datamanager.handlers.MBRESTServiceDataHandler.java

private void allowAnyCertificate(HttpClient httpClient)
        throws KeyManagementException, NoSuchAlgorithmException {
    SSLContext ctx = SSLContext.getInstance("TLS");
    X509TrustManager tm = new X509TrustManager() {

        @Override//from  www  . ja v  a2s  .  c o  m
        public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };
    ctx.init(null, new TrustManager[] { tm }, null);
    SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    ClientConnectionManager ccm = httpClient.getConnectionManager();
    SchemeRegistry sr = ccm.getSchemeRegistry();
    sr.register(new Scheme("https", 443, ssf));
}

From source file:com.evrythng.java.wrapper.core.api.ApiCommand.java

private static HttpClient wrapClient(final HttpClient base) {

    try {/*  w  w  w.j ava 2 s .c  om*/
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        SSLSocketFactory ssf = new WrapperSSLSocketFactory(trustStore);
        ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = base.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", ssf, 443));
        return new DefaultHttpClient(ccm, base.getParams());
    } catch (Exception ex) {
        return null;
    }
}

From source file:org.dasein.cloud.google.HttpsConnection.java

public static String getJSON(String iss, String p12File) throws Exception {
    System.out.println("ISS : " + iss);
    System.out.println("P12File : " + p12File);

    HttpClient client = new DefaultHttpClient();
    List formparams = new ArrayList();
    formparams.add(new BasicNameValuePair("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"));
    formparams.add(new BasicNameValuePair("assertion", GenerateToken.getToken(iss, p12File)));
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");

    //      HttpClient client1 = new HttpClient();
    String url = "https://accounts.google.com/o/oauth2/token";
    //      System.out.println(url);
    //      PostMethod pm = new PostMethod(url); 
    //      pm.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    //      pm.addRequestHeader("Host", "accounts.google.com");
    ////      pm.addRequestHeader("Host", "accounts.google.com");
    //      pm.addParameter("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer");
    //      pm.addParameter("assertion", GenerateToken.getData());
    ////      System.out.println(C.getData());
    ////from  w  ww  . j  av a  2  s. c o m
    //      int statusCode = client1.executeMethod(pm);

    HttpPost httppost = new HttpPost(url);
    httppost.addHeader("Content-Type", "application/x-www-form-urlencoded");
    httppost.setEntity(entity);
    HttpResponse httpResponse1 = client.execute(httppost);
    int s1 = httpResponse1.getStatusLine().getStatusCode();
    if (s1 == HttpStatus.SC_OK) {
        try {
            //   InputStream in = getResponseBody(pm);
            InputStream in = httpResponse1.getEntity().getContent();
            writeToFile(in, "D:\\google_out.txt");
            System.out.println(printFile("D:\\google_out.txt"));
        } catch (Exception e) {
            System.out.println("No response body !");
        }
    }

    JSONObject obj1 = new JSONObject(printFile("D:\\google_out.txt"));
    String access_token = obj1.getString("access_token");
    String token_type = obj1.getString("token_type");
    String expires_in = obj1.getString("expires_in");
    String resource = "instances";
    url = "https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/zones/us-east1-a/"
            + resource + "?access_token=" + access_token + "&token_type=Bearer&expires_in=3600";
    String str = "{"
            + "\"image\": \"https://www.googleapis.com/compute/v1beta14/projects/google/global/images/gcel-10-04-v20130104\","
            + "\"machineType\": \"https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/global/machineTypes/n1-standard-1\","
            + "\"name\": \"trial\","
            + "\"zone\": \"https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/zones/us-east1-a/\","
            + "\"networkInterfaces\": [ {  \"network\": \"https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/networks/default\" } ],"
            + "\"disks\": [ { \"type\": \"EPHEMERAL\",  \"deleteOnTerminate\": true  } ], \"metadata\": { \"items\": [ ],  \"kind\": \"compute#metadata\" }}";
    System.out.println(str);
    JSONObject json = new JSONObject(str);
    System.out.println("POST Methods : " + url);
    StringEntity se = new StringEntity(str);
    JSONObject json1 = new JSONObject();
    json1.put("image",
            "https://www.googleapis.com/compute/v1beta14/projects/google/global/images/gcel-10-04-v20130104");
    json1.put("machineType",
            "https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/global/machineTypes/n1-standard-1");
    json1.put("name", "trial");
    json1.put("zone",
            "https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/zones/us-east1-a/");
    //json1.put("image", "https://www.googleapis.com/compute/v1beta13/projects/google/images/ubuntu-10-04-v20120621");
    System.out.println(" JSON 1 : " + json.toString() + " \n JSON 2 : " + json1.toString());
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
    nameValuePairs.add(new BasicNameValuePair("json", str));

    //              
    //               JSONObject jsonPayload = null;
    //               JSONObject obj = new JSONObject();
    //               
    //               try {
    //               obj.put("name", "vinotrial");
    //               obj.put("IPv4Range", "192.0.0.0/16");
    //               obj.put("description", "wrwer");
    //
    //               } catch (Exception e) {
    //                  
    //               }

    /*
    JSONObject jsonPayload = null;
    JSONObject obj = new JSONObject();
            
    try {
    obj.put("name", "testCreateStandardFirewall1734".toLowerCase());
    obj.put("description", "SSH allowed from anywhere");
    obj.put("network", "https://www.googleapis.com/compute/v1beta13/projects/enstratus.com:enstratus-dev/networks/default");
    JSONArray sranges = new JSONArray();
    JSONArray allowed = new JSONArray();
    JSONObject allowedtemp = new JSONObject();
    JSONArray ports = new JSONArray();
    allowedtemp.put("IPProtocol", "tcp");
    ports.put("22");
    allowedtemp.put("ports", ports);
    allowed.put(allowedtemp);
    //               
    //               JSONObject allowedtemp1 = new JSONObject();
    //               JSONArray ports1 = new JSONArray();
    //               allowedtemp1.put("IPProtocol", "udp");
    //               ports1.put("1-65535");
    //               allowedtemp1.put("ports", ports1);
    //               allowed.put(allowedtemp1);
    //               
    //               
    //               
    //               JSONObject allowedtemp2 = new JSONObject();
    //               
    //               allowedtemp2.put("IPProtocol", "icmp");
    //               
    //               allowed.put(allowedtemp2);
            
            
    sranges.put("0.0.0.0/0");
    obj.put("sourceRanges", sranges);
    obj.put("allowed", allowed);
    } catch (Exception e) {
             
    }
            
            
    */

    //UrlEncodedFormEntity entity1 = new UrlEncodedFormEntity(formparams1, "UTF-8");
    System.out.println("Creating an instance");
    HttpPost httppost1 = new HttpPost(url);
    httppost1.setHeader("Content-type", "application/json");
    //httppost1.addHeader("X-JavaScript-User-Agent", "trov");
    //httppost1.setEntity(se);
    //   httppost1.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    System.out.println("payload:" + json1.toString());
    System.out.println("url:" + url);
    StringEntity se1 = new StringEntity(json1.toString());
    se1.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
    httppost1.setEntity(se1);
    //

    HttpClient base = new DefaultHttpClient();
    SSLContext ctx = SSLContext.getInstance("TLS");
    X509TrustManager tm = new X509TrustManager() {

        public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
        }

        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };
    ctx.init(null, new TrustManager[] { tm }, null);
    SSLSocketFactory ssf = new SSLSocketFactory(ctx);
    ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    ClientConnectionManager ccm = base.getConnectionManager();
    SchemeRegistry sr = ccm.getSchemeRegistry();
    sr.register(new Scheme("https", ssf, 443));
    HttpClient client1 = new DefaultHttpClient(ccm);

    //HttpClient client1 = new DefaultHttpClient();
    HttpResponse httpResponse2 = client1.execute(httppost1);
    int s2 = httpResponse2.getStatusLine().getStatusCode();
    if (s2 == HttpStatus.SC_OK) {
        try {
            //   InputStream in = getResponseBody(pm);
            InputStream in = httpResponse2.getEntity().getContent();
            writeToFile(in, "D:\\google_out.txt");
            System.out.println(printFile("D:\\google_out.txt"));
        } catch (Exception e) {
            System.out.println("No response body !");
        }
    } else {
        System.out.println("Instance creation failed with error status " + s2);
        InputStream in = httpResponse2.getEntity().getContent();
        writeToFile(in, "D:\\google_out.txt");
        System.out.println(printFile("D:\\google_out.txt"));
    }

    String[] Zone = { "europe-west1-a", "europe-west1-b", "us-central1-a", "us-central1-b", "us-central2-a",
            "us-east1-a" };
    for (String zone : Zone) {
        //             {
        HttpClient client3 = new DefaultHttpClient();
        resource = "instances";
        System.out.println("listing the instances !");
        //      url= "https://www.googleapis.com/compute/v1beta13/projects/google/kernels?access_token=" + access_token + "&token_type=Bearer&expires_in=3600" ;
        url = "https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/zones/us-central1-a/"
                + resource + "?access_token=" + access_token + "&token_type=Bearer&expires_in=3600";
        //   url = "https://www.googleapis.com/compute/v1beta13/projects/enstratus.com:enstratus-dev?access_token=" + access_token + "&token_type=Bearer&expires_in=3600" ;
        //         url = "https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/zones/us-east1-a/instances?access_token=" + access_token + "&token_type=Bearer&expires_in=3600" ;
        System.out.println("url : -----------" + url);

        JSONArray items = new JSONArray();

        HttpGet method = new HttpGet(url);

        HttpResponse httpResponse = client3.execute(method);
        int s = httpResponse.getStatusLine().getStatusCode();

        if (s == HttpStatus.SC_OK) {

            try {
                System.out.println("\nResponse from Server : ");
                //InputStream in = getResponseBody(gm);
                InputStream in = httpResponse.getEntity().getContent();
                writeToFile(in, "D:\\calendar_out.txt");
                String str1 = printFile("D:\\calendar_out.txt");
                System.out.println(str1);
                JSONObject jsonO = new JSONObject(str1);
                items = (JSONArray) jsonO.get("items");

                //   return printFile("D:\\calendar_out.txt");
            } catch (Exception e) {
                System.out.println("No response body !" + e.getLocalizedMessage());
            }

        } else
            System.out.println(httpResponse);

        for (int i = 0; i < items.length(); i++) {

            JSONObject item = (JSONObject) items.get(i);
            String name = null;
            if (item.has("name"))
                name = (String) item.get("name");
            //System.out.println("instance : " + name);

            if (!name.contains("default")) {
                System.out.println("Deleting the instance " + name);
                url = "https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/zones/us-central1-a/"
                        + resource + "/" + name + "?access_token=" + access_token
                        + "&token_type=Bearer&expires_in=3600";
                System.out.println("url : " + url);

                HttpDelete delMethod = new HttpDelete(url);
                HttpResponse httpResponse3 = client.execute(delMethod);
                int s3 = httpResponse3.getStatusLine().getStatusCode();
                if (s3 == HttpStatus.SC_OK) {

                    try {
                        System.out.println("\nResponse from Server : ");
                        //InputStream in = getResponseBody(gm);
                        InputStream in = httpResponse3.getEntity().getContent();
                        writeToFile(in, "D:\\calendar_out.txt");
                        System.out.println(printFile("D:\\calendar_out.txt"));
                        //   return printFile("D:\\calendar_out.txt");
                    } catch (Exception e) {
                        System.out.println("No response body !");

                    }

                } else {
                    System.out.println("Deleting failed with status : " + s3);
                    try {
                        InputStream in = httpResponse3.getEntity().getContent();
                        writeToFile(in, "D:\\calendar_out.txt");
                        System.out.println(printFile("D:\\calendar_out.txt"));
                    } catch (Exception e) {

                    }
                }
            }
        }

        //      https://www.googleapis.com/compute/v1beta13/projects/enstratus.com%3Aenstratus-dev/instances/trial
        //      GetMethod gm      = new GetMethod(url); 
        //      HttpMethodParams params = new HttpMethodParams();
        ////      params.setParameter("calendarId", "vidhyanallasamy%40gmail.com");
        //      gm.setParams(params);
        //
        //      statusCode = client1.executeMethod(gm);
        //      System.out.println("\nStatus Code : " + statusCode);
        //
        //      try {
        //         System.out.println("\nResponse from Server : ");
        //         InputStream in = getResponseBody(gm);
        //         writeToFile(in, "D:\\calendar_out.txt");
        //         System.out.println(printFile("D:\\calendar_out.txt"));
        //      } catch (Exception e) {
        //         System.out.println("No response body !");
        //      }\
    }
    return null;
}

From source file:com.pyj.http.AsyncHttpClient.java

private SSLSocketFactory getSSLSocketFactory() {
    SSLSocketFactory sf = null;/* w ww  .  j a  v  a 2 s . c o  m*/
    try {
        KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());
        store.load(null, null);
        sf = new SSLSocketFactoryEx(store);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); // ??
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (CertificateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return sf;
}

From source file:com.google.wireless.speed.speedometer.Checkin.java

/**
 * Return an appropriately-configured HTTP client.
 *///from   w ww .ja  v  a  2s .  c o m
private HttpClient getNewHttpClient() {
    DefaultHttpClient client;
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new MySSLSocketFactory(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);

        HttpConnectionParams.setConnectionTimeout(params, POST_TIMEOUT_MILLISEC);
        HttpConnectionParams.setSoTimeout(params, POST_TIMEOUT_MILLISEC);

        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);
        client = new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        Log.w(SpeedometerApp.TAG, "Unable to create SSL HTTP client", e);
        client = new DefaultHttpClient();
    }

    // TODO(mdw): For some reason this is not sending the cookie to the
    // test server, probably because the cookie itself is not properly
    // initialized. Below I manually set the Cookie header instead.
    CookieStore store = new BasicCookieStore();
    store.addCookie(authCookie);
    client.setCookieStore(store);
    return client;
}