Example usage for javax.net.ssl HttpsURLConnection setSSLSocketFactory

List of usage examples for javax.net.ssl HttpsURLConnection setSSLSocketFactory

Introduction

In this page you can find the example usage for javax.net.ssl HttpsURLConnection setSSLSocketFactory.

Prototype

public void setSSLSocketFactory(SSLSocketFactory sf) 

Source Link

Document

Sets the <code>SSLSocketFactory</code> to be used when this instance creates sockets for secure https URL connections.

Usage

From source file:com.hichinaschool.flashcards.async.Connection.java

private Payload doInBackgroundDownloadSharedDeck(Payload data) {
    String url = (String) data.data[0];
    String colFilename = AnkiDroidApp.getCurrentAnkiDroidDirectory() + "/tmpImportFile.apkg";
    URL fileUrl;// w  w w.ja v a  2s . com
    URLConnection conn;
    InputStream cont = null;
    try {
        fileUrl = new URL(url);
        if (url.startsWith("https")) {
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, new TrustManager[] { new EasyX509TrustManager(null) }, null);
            HttpsURLConnection httpsConn = (HttpsURLConnection) fileUrl.openConnection();
            httpsConn.setSSLSocketFactory(context.getSocketFactory());
            conn = httpsConn;
        } else {
            conn = (HttpURLConnection) fileUrl.openConnection();
        }
        conn.setConnectTimeout(10000);
        conn.setReadTimeout(10000);
        cont = conn.getInputStream();
    } catch (MalformedURLException e) {
        Log.e(AnkiDroidApp.TAG, "doInBackgroundDownloadSharedDeck: ", e);
        data.success = false;
        return data;
    } catch (IOException e) {
        Log.e(AnkiDroidApp.TAG, "doInBackgroundDownloadSharedDeck: ", e);
        data.success = false;
        return data;
    } catch (NoSuchAlgorithmException e) {
        Log.e(AnkiDroidApp.TAG, "doInBackgroundDownloadSharedDeck: ", e);
        data.success = false;
        return data;
    } catch (KeyStoreException e) {
        Log.e(AnkiDroidApp.TAG, "doInBackgroundDownloadSharedDeck: ", e);
        return data;
    } catch (KeyManagementException e) {
        Log.e(AnkiDroidApp.TAG, "doInBackgroundDownloadSharedDeck: ", e);
        data.success = false;
        return data;
    }
    if (cont == null) {
        data.success = false;
        return data;
    }
    File file = new File(colFilename);
    OutputStream output = null;
    try {
        file.createNewFile();
        output = new BufferedOutputStream(new FileOutputStream(file));
        byte[] buf = new byte[Utils.CHUNK_SIZE];
        int len;
        int count = 0;
        while ((len = cont.read(buf)) >= 0) {
            output.write(buf, 0, len);
            count += len;
            publishProgress(new Object[] { count / 1024 });
        }
        output.close();
    } catch (IOException e) {
        try {
            output.close();
        } catch (IOException e1) {
            // do nothing
        }
        // no write access or sd card full
        file.delete();
        data.success = false;
        return data;
    }
    data.success = true;
    data.result = colFilename;
    return data;
}

From source file:org.matrix.androidsdk.db.MXMediaDownloadWorkerTask.java

@Override
protected Void doInBackground(Integer... params) {
    try {/*from  w  w w . j  a va  2s.c  om*/
        URL url = new URL(mUrl);
        Log.d(LOG_TAG, "MXMediaDownloadWorkerTask " + this + " starts");

        mDownloadStats = new IMXMediaDownloadListener.DownloadStats();
        // don't known yet
        mDownloadStats.mEstimatedRemainingTime = -1;

        InputStream stream = null;

        int filelen = -1;
        URLConnection connection = null;

        try {
            connection = url.openConnection();

            if (mHsConfig != null && connection instanceof HttpsURLConnection) {
                // Add SSL Socket factory.
                HttpsURLConnection sslConn = (HttpsURLConnection) connection;
                try {
                    Pair<SSLSocketFactory, X509TrustManager> pair = CertUtil
                            .newPinnedSSLSocketFactory(mHsConfig);
                    sslConn.setSSLSocketFactory(pair.first);
                    sslConn.setHostnameVerifier(CertUtil.newHostnameVerifier(mHsConfig));
                } catch (Exception e) {
                    Log.e(LOG_TAG, "doInBackground SSL exception " + e.getLocalizedMessage());
                }
            }

            // add a timeout to avoid infinite loading display.
            connection.setReadTimeout(DOWNLOAD_TIME_OUT);
            filelen = connection.getContentLength();
            stream = connection.getInputStream();
        } catch (Exception e) {
            Log.e(LOG_TAG, "bitmapForURL : fail to open the connection " + e.getMessage());

            InputStream errorStream = ((HttpsURLConnection) connection).getErrorStream();

            if (null != errorStream) {
                try {
                    BufferedReader streamReader = new BufferedReader(
                            new InputStreamReader(errorStream, "UTF-8"));
                    StringBuilder responseStrBuilder = new StringBuilder();

                    String inputStr;

                    while ((inputStr = streamReader.readLine()) != null) {
                        responseStrBuilder.append(inputStr);
                    }

                    mErrorAsJsonElement = new JsonParser().parse(responseStrBuilder.toString());
                } catch (Exception ee) {
                    Log.e(LOG_TAG, "bitmapForURL : Error parsing error " + ee.getLocalizedMessage());
                }
            }

            // privacy
            //Log.d(LOG_TAG, "MediaWorkerTask " + mUrl + " does not exist");
            Log.d(LOG_TAG, "MediaWorkerTask an url does not exist");

            // if some medias are not found
            // do not try to reload them until the next application launch.
            synchronized (mUnreachableUrls) {
                mUnreachableUrls.add(mUrl);
            }
        }

        dispatchDownloadStart();

        // test if the download has not been cancelled
        if (!isDownloadCancelled() && (null == mErrorAsJsonElement)) {

            final long startDownloadTime = System.currentTimeMillis();

            String filename = MXMediaDownloadWorkerTask.buildFileName(mUrl, mMimeType) + ".tmp";
            FileOutputStream fos = new FileOutputStream(new File(mDirectoryFile, filename));

            mDownloadStats.mDownloadId = mUrl;
            mDownloadStats.mProgress = 0;
            mDownloadStats.mDownloadedSize = 0;
            mDownloadStats.mFileSize = filelen;
            mDownloadStats.mElapsedTime = 0;
            mDownloadStats.mEstimatedRemainingTime = -1;
            mDownloadStats.mBitRate = 0;

            final android.os.Handler uiHandler = new android.os.Handler(Looper.getMainLooper());

            final Timer refreshTimer = new Timer();

            uiHandler.post(new Runnable() {
                @Override
                public void run() {
                    refreshTimer.scheduleAtFixedRate(new TimerTask() {
                        @Override
                        public void run() {
                            uiHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    if (!mIsDone) {
                                        publishProgress(startDownloadTime);
                                    }
                                }
                            });
                        }
                    }, new java.util.Date(), 100);
                }
            });

            try {
                byte[] buf = new byte[DOWNLOAD_BUFFER_READ_SIZE];
                int len;
                while (!isDownloadCancelled() && (len = stream.read(buf)) != -1) {
                    fos.write(buf, 0, len);
                    mDownloadStats.mDownloadedSize += len;
                }

                if (!isDownloadCancelled()) {
                    mDownloadStats.mProgress = 100;
                }
            } catch (OutOfMemoryError outOfMemoryError) {
                Log.e(LOG_TAG, "doInBackground: out of memory");
            } catch (Exception e) {
                Log.e(LOG_TAG, "doInBackground fail to read image " + e.getMessage());
            }

            mIsDone = true;

            close(stream);
            fos.flush();
            fos.close();

            if (null != mEncryptedFileInfo) {
                File file = new File(mDirectoryFile, filename);
                FileInputStream fis = new FileInputStream(file);
                InputStream is = MXEncryptedAttachments.decryptAttachment(fis, mEncryptedFileInfo);
                fis.close();

                // if the decryption succeeds, replace the encrypted file content by the unencrypted one
                if (null != is) {
                    mApplicationContext.deleteFile(filename);

                    fos = new FileOutputStream(file);
                    byte[] buf = new byte[DOWNLOAD_BUFFER_READ_SIZE];
                    int len;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }
                } else {
                    mDownloadStats.mProgress = 0;
                }
            }

            uiHandler.post(new Runnable() {
                @Override
                public void run() {
                    refreshTimer.cancel();
                }
            });

            if ((null != connection) && (connection instanceof HttpsURLConnection)) {
                ((HttpsURLConnection) connection).disconnect();
            }

            // the file has been successfully downloaded
            if (mDownloadStats.mProgress == 100) {
                try {
                    File originalFile = new File(mDirectoryFile, filename);
                    String newFileName = MXMediaDownloadWorkerTask.buildFileName(mUrl, mMimeType);
                    File newFile = new File(mDirectoryFile, newFileName);
                    if (newFile.exists()) {
                        // Or you could throw here.
                        mApplicationContext.deleteFile(newFileName);
                    }
                    originalFile.renameTo(newFile);
                } catch (Exception e) {
                    Log.e(LOG_TAG, "doInBackground : renaming error " + e.getLocalizedMessage());
                }
            }
        }

        if (mDownloadStats.mProgress == 100) {
            Log.d(LOG_TAG, "The download " + this + " is done.");
        } else {
            if (null != mErrorAsJsonElement) {
                Log.d(LOG_TAG, "The download " + this + " failed : mErrorAsJsonElement "
                        + mErrorAsJsonElement.toString());
            } else {
                Log.d(LOG_TAG, "The download " + this + " failed.");
            }
        }
    } catch (Exception e) {
        Log.e(LOG_TAG, "Unable to download media " + this);
    }

    // remove the image from the loading one
    synchronized (mPendingDownloadByUrl) {
        mPendingDownloadByUrl.remove(mUrl);
    }

    return null;
}

From source file:org.fabric3.admin.interpreter.communication.DomainConnectionImpl.java

private void setSocketFactory(HttpsURLConnection connection) throws CommunicationException {
    try {//from   w  w w. j a  v a 2 s. c  om
        if (sslFactory == null) {
            // initialize the SSL context
            String keyStoreLocation = getKeystoreLocation();
            if (keyStoreLocation == null) {
                throw new CommunicationException(
                        "Keystore not configured. A keystore must be placed in /config when using SSL.");
            }
            System.setProperty(KEY_STORE, keyStoreLocation);
            System.setProperty(TRUST_STORE, keyStoreLocation);
            KeyStore keyStore = KeyStore.getInstance("JKS");
            InputStream stream = new FileInputStream(keyStoreLocation);
            keyStore.load(stream, null);

            TrustManagerFactory tmf = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            tmf.init(keyStore);
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, tmf.getTrustManagers(), null);
            sslFactory = ctx.getSocketFactory();
        }
        connection.setSSLSocketFactory(sslFactory);
    } catch (NoSuchAlgorithmException | CertificateException | KeyManagementException | KeyStoreException
            | IOException e) {
        throw new CommunicationException(e);
    }
}

From source file:android.webkit.cts.CtsTestServer.java

private URLConnection openConnection(URL url)
        throws IOException, NoSuchAlgorithmException, KeyManagementException {
    if (mSsl == SslMode.INSECURE) {
        return url.openConnection();
    } else {/*from w  w w  . jav  a  2s .  c  o  m*/
        // Install hostname verifiers and trust managers that don't do
        // anything in order to get around the client not trusting
        // the test server due to a lack of certificates.

        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        connection.setHostnameVerifier(new CtsHostnameVerifier());

        SSLContext context = SSLContext.getInstance("TLS");
        try {
            context.init(ServerThread.getKeyManagers(), getTrustManagers(), null);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        connection.setSSLSocketFactory(context.getSocketFactory());

        return connection;
    }
}

From source file:se.leap.bitmaskclient.ProviderAPI.java

/**
 * Executes an HTTP request expecting a JSON response.
 *
 * @param url//from  ww w. j  av a 2 s .  c o  m
 * @param request_method
 * @param parameters
 * @return response from authentication server
 */
private JSONObject sendToServer(String url, String request_method, Map<String, String> parameters) {
    JSONObject json_response;
    HttpsURLConnection urlConnection = null;
    try {
        InputStream is = null;
        urlConnection = (HttpsURLConnection) new URL(url).openConnection();
        urlConnection.setRequestMethod(request_method);
        String locale = Locale.getDefault().getLanguage() + Locale.getDefault().getCountry();
        urlConnection.setRequestProperty("Accept-Language", locale);
        urlConnection.setChunkedStreamingMode(0);
        urlConnection.setSSLSocketFactory(getProviderSSLSocketFactory());

        DataOutputStream writer = new DataOutputStream(urlConnection.getOutputStream());
        writer.writeBytes(formatHttpParameters(parameters));
        writer.close();

        is = urlConnection.getInputStream();
        String plain_response = new Scanner(is).useDelimiter("\\A").next();
        json_response = new JSONObject(plain_response);
    } catch (ClientProtocolException e) {
        json_response = getErrorMessage(urlConnection);
        e.printStackTrace();
    } catch (IOException e) {
        json_response = getErrorMessage(urlConnection);
        e.printStackTrace();
    } catch (JSONException e) {
        json_response = getErrorMessage(urlConnection);
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        json_response = getErrorMessage(urlConnection);
        e.printStackTrace();
    } catch (KeyManagementException e) {
        json_response = getErrorMessage(urlConnection);
        e.printStackTrace();
    } catch (KeyStoreException e) {
        json_response = getErrorMessage(urlConnection);
        e.printStackTrace();
    } catch (CertificateException e) {
        json_response = getErrorMessage(urlConnection);
        e.printStackTrace();
    }

    return json_response;
}

From source file:org.globusonline.nexus.BaseNexusRestClient.java

/**
 * @param path//from   w ww. j a v a 2 s  .  c o  m
 * @return JSON Response from action
 * @throws NexusClientException
 */
protected JSONObject issueRestRequest(String path, String httpMethod, String contentType, String accept,
        JSONObject params, NexusAuthenticator auth) throws NexusClientException {

    JSONObject json = null;

    HttpsURLConnection connection;

    if (httpMethod.isEmpty()) {
        httpMethod = "GET";
    }
    if (contentType.isEmpty()) {
        contentType = "application/json";
    }
    if (accept.isEmpty()) {
        accept = "application/json";
    }
    int responseCode;

    try {

        URL url = new URL(getNexusApiUrl() + path);

        connection = (HttpsURLConnection) url.openConnection();

        if (ignoreCertErrors) {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new SecureRandom());
            connection.setSSLSocketFactory(sc.getSocketFactory());
            connection.setHostnameVerifier(allHostsValid);
        }

        if (auth != null) {
            auth.authenticate(connection);
        }

        connection.setDoOutput(true);
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod(httpMethod);
        connection.setRequestProperty("Content-Type", contentType);
        connection.setRequestProperty("Accept", accept);
        connection.setRequestProperty("X-Go-Community-Context", community);

        String body = "";

        if (params != null) {
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
            body = params.toString();
            out.write(body);
            logger.debug("Body:" + body);
            out.close();
        }

        responseCode = connection.getResponseCode();

    } catch (Exception e) {
        logger.error("Unhandled connection error:", e);
        throw new ValueErrorException();
    }

    logger.info("ConnectionURL: " + connection.getURL());

    if (responseCode == 403 || responseCode == 400) {
        logger.error("Access is denied.  Invalid credentials.");
        throw new InvalidCredentialsException();
    }
    if (responseCode == 404) {
        logger.error("URL not found.");
        throw new InvalidUrlException();
    }
    if (responseCode == 500) {
        logger.error("Internal Server Error.");
        throw new ValueErrorException();
    }
    if (responseCode != 200) {
        logger.info("Response code is: " + responseCode);
    }

    try {
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String decodedString = in.readLine();

        json = new JSONObject(decodedString);
    } catch (JSONException e) {
        logger.error("JSON Error", e);
        throw new ValueErrorException();
    } catch (IOException e) {
        logger.error("IO Error", e);
        throw new ValueErrorException();
    }

    return json;
}

From source file:com.wwpass.connection.WWPassConnection.java

private InputStream makeRequest(String method, String command, Map<String, ?> parameters)
        throws IOException, WWPassProtocolException {
    String commandUrl = SpfeURL + command + ".xml";
    //String command_url = SpfeURL + command + ".json";

    StringBuilder sb = new StringBuilder();
    URLCodec codec = new URLCodec();

    @SuppressWarnings("unchecked")
    Map<String, Object> localParams = (Map<String, Object>) parameters;

    for (Map.Entry<String, Object> entry : localParams.entrySet()) {
        sb.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
        sb.append("=");
        if (entry.getValue() instanceof String) {
            sb.append(URLEncoder.encode((String) entry.getValue(), "UTF-8"));
        } else {//from  www  . j a  v a  2 s  . c o  m
            sb.append(new String(codec.encode((byte[]) entry.getValue())));
        }
        sb.append("&");
    }
    String paramsString = sb.toString();
    sb = null;
    if ("GET".equalsIgnoreCase(method)) {
        commandUrl += "?" + paramsString;
    } else if ("POST".equalsIgnoreCase(method)) {

    } else {
        throw new IllegalArgumentException("Method " + method + " not supported.");
    }

    HttpsURLConnection conn = null;
    try {
        URL url = new URL(commandUrl);
        conn = (HttpsURLConnection) url.openConnection();
        conn.setReadTimeout(timeoutMs);
        conn.setSSLSocketFactory(SPFEContext.getSocketFactory());
        if ("POST".equalsIgnoreCase(method)) {
            conn.setDoOutput(true);
            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
            writer.write(paramsString);
            writer.flush();
        }
        InputStream in = conn.getInputStream();
        return getReplyData(in);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("Command-parameters combination is invalid: " + e.getMessage());
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:org.apache.nifi.controller.livy.LivySessionController.java

private void setSslSocketFactory(HttpsURLConnection httpsURLConnection, SSLContextService sslService,
        SSLContext sslContext) throws IOException, KeyStoreException, CertificateException,
        NoSuchAlgorithmException, UnrecoverableKeyException, KeyManagementException {
    final String keystoreLocation = sslService.getKeyStoreFile();
    final String keystorePass = sslService.getKeyStorePassword();
    final String keystoreType = sslService.getKeyStoreType();

    // prepare the keystore
    final KeyStore keyStore = KeyStore.getInstance(keystoreType);

    try (FileInputStream keyStoreStream = new FileInputStream(keystoreLocation)) {
        keyStore.load(keyStoreStream, keystorePass.toCharArray());
    }/*  w  w w  .  j  a v  a  2  s . co m*/

    final KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, keystorePass.toCharArray());

    // load truststore
    final String truststoreLocation = sslService.getTrustStoreFile();
    final String truststorePass = sslService.getTrustStorePassword();
    final String truststoreType = sslService.getTrustStoreType();

    KeyStore truststore = KeyStore.getInstance(truststoreType);
    final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("X509");
    truststore.load(new FileInputStream(truststoreLocation), truststorePass.toCharArray());
    trustManagerFactory.init(truststore);

    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

    final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
    httpsURLConnection.setSSLSocketFactory(sslSocketFactory);
}

From source file:com.spotify.sshagenttls.CertHttpsHandler.java

public void handle(final HttpsURLConnection conn) {
    final CertKey certKey;
    try {//w ww. j a v  a2  s . c o  m
        certKey = createCertKey();
    } catch (IOException | GeneralSecurityException e) {
        if (failOnCertError) {
            throw new RuntimeException(e);
        } else {
            LOG.warn("Error when setting up client certificates fromPaths {}. Error was '{}'. "
                    + "No cert will be sent with request.", getCertSource(), e.toString());
            LOG.debug("full exception fromPaths setting up ClientCertificate follows", e);
            return;
        }
    }

    final Certificate cert = certKey.cert();
    final PrivateKey key = certKey.key();

    // Generate a keystore password.
    // Do all this locally to not make copies of the password in memory.
    final SecureRandom random = new SecureRandom();
    final int numBytes = 60;
    final char[] keyStorePassword = new char[numBytes];
    for (int i = 0; i < numBytes; i++) {
        // Only use ASCII characters for the password. The corresponding integer range is [32, 126].
        keyStorePassword[i] = (char) (random.nextInt(95) + 32);
    }

    try {
        // We're creating a keystore in memory and putting the cert & key into it.
        // The keystore needs a password when we put the key into it, even though it's only going to
        // exist for the lifetime of the process. So we just have some random password that we use.

        final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        keyStore.setCertificateEntry("client", cert);
        keyStore.setKeyEntry("key", key, keyStorePassword, new Certificate[] { cert });

        // build an SSLContext based on our keystore, and then get an SSLSocketFactory fromPaths that
        final SSLContext sslContext = SSLContexts.custom().useProtocol("TLS")
                .loadKeyMaterial(keyStore, keyStorePassword).build();

        // Clear out arrays that had password
        Arrays.fill(keyStorePassword, '\0');

        conn.setSSLSocketFactory(sslContext.getSocketFactory());
    } catch (CertificateException | IOException | NoSuchAlgorithmException | KeyStoreException
            | UnrecoverableKeyException | KeyManagementException e) {
        // so many dumb ways to die. see https://www.youtube.com/watch?v=IJNR2EpS0jw for more.
        throw new RuntimeException(e);
    }
}

From source file:org.pixmob.fm2.util.HttpUtils.java

/**
 * Setup SSL connection./*from   w ww.ja  v  a 2  s.c om*/
 */
private static void setupSecureConnection(Context context, HttpsURLConnection conn) throws IOException {
    if (DEBUG) {
        Log.d(TAG, "Load custom SSL certificates");
    }

    final SSLContext sslContext;
    try {
        // Load SSL certificates:
        // http://nelenkov.blogspot.com/2011/12/using-custom-certificate-trust-store-on.html
        // Earlier Android versions do not have updated root CA
        // certificates, resulting in connection errors.
        final KeyStore keyStore = loadCertificates(context);

        final CustomTrustManager customTrustManager = new CustomTrustManager(keyStore);
        final TrustManager[] tms = new TrustManager[] { customTrustManager };

        // Init SSL connection with custom certificates.
        // The same SecureRandom instance is used for every connection to
        // speed up initialization.
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, tms, SECURE_RANDOM);
    } catch (GeneralSecurityException e) {
        final IOException ioe = new IOException("Failed to initialize SSL engine");
        ioe.initCause(e);
        throw ioe;
    }

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        // Fix slow read:
        // http://code.google.com/p/android/issues/detail?id=13117
        // Prior to ICS, the host name is still resolved even if we already
        // know its IP address, for each connection.
        final SSLSocketFactory delegate = sslContext.getSocketFactory();
        final SSLSocketFactory socketFactory = new SSLSocketFactory() {
            @Override
            public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
                InetAddress addr = InetAddress.getByName(host);
                injectHostname(addr, host);
                return delegate.createSocket(addr, port);
            }

            @Override
            public Socket createSocket(InetAddress host, int port) throws IOException {
                return delegate.createSocket(host, port);
            }

            @Override
            public Socket createSocket(String host, int port, InetAddress localHost, int localPort)
                    throws IOException, UnknownHostException {
                return delegate.createSocket(host, port, localHost, localPort);
            }

            @Override
            public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort)
                    throws IOException {
                return delegate.createSocket(address, port, localAddress, localPort);
            }

            private void injectHostname(InetAddress address, String host) {
                try {
                    Field field = InetAddress.class.getDeclaredField("hostName");
                    field.setAccessible(true);
                    field.set(address, host);
                } catch (Exception ignored) {
                }
            }

            @Override
            public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
                injectHostname(s.getInetAddress(), host);
                return delegate.createSocket(s, host, port, autoClose);
            }

            @Override
            public String[] getDefaultCipherSuites() {
                return delegate.getDefaultCipherSuites();
            }

            @Override
            public String[] getSupportedCipherSuites() {
                return delegate.getSupportedCipherSuites();
            }
        };
        conn.setSSLSocketFactory(socketFactory);
    } else {
        conn.setSSLSocketFactory(sslContext.getSocketFactory());
    }

    conn.setHostnameVerifier(new BrowserCompatHostnameVerifier());
}