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:xin.nic.sdk.registrar.util.HttpUtil.java

/**
 * ??HTTPS GET//from  www  .  j  ava 2s . c  o m
 * 
 * @param url URL
 * @return 
 */
public static HttpResp doHttpsGet(URL url) {

    HttpsURLConnection conn = null;
    InputStream inputStream = null;
    Reader reader = null;

    try {
        // ???httphttps
        String protocol = url.getProtocol();
        if (!PROTOCOL_HTTPS.equals(protocol)) {
            throw new XinException("xin.error.url", "?https");
        }

        // 
        conn = (HttpsURLConnection) url.openConnection();

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, tmArr, new SecureRandom());

        conn.setSSLSocketFactory(sc.getSocketFactory());

        // ?
        conn.setConnectTimeout(connTimeout);
        conn.setReadTimeout(readTimeout);
        conn.setDoOutput(true);
        conn.setDoInput(true);

        // UserAgent
        conn.setRequestProperty("User-Agent", "java-sdk");

        // ?
        conn.connect();

        // ?
        inputStream = conn.getInputStream();
        reader = new InputStreamReader(inputStream, charset);
        BufferedReader bufferReader = new BufferedReader(reader);
        StringBuilder stringBuilder = new StringBuilder();
        String inputLine = "";
        while ((inputLine = bufferReader.readLine()) != null) {
            stringBuilder.append(inputLine);
            stringBuilder.append("\n");
        }

        // 
        HttpResp resp = new HttpResp();
        resp.setStatusCode(conn.getResponseCode());
        resp.setStatusPhrase(conn.getResponseMessage());
        resp.setContent(stringBuilder.toString());

        // 
        return resp;
    } catch (MalformedURLException e) {
        throw new XinException("xin.error.url", "url:" + url + ", url?");
    } catch (IOException e) {
        throw new XinException("xin.error.http", String.format("IOException:%s", e.getMessage()));
    } catch (KeyManagementException e) {
        throw new XinException("xin.error.url", "url:" + url + ", url?");
    } catch (NoSuchAlgorithmException e) {
        throw new XinException("xin.error.url", "url:" + url + ", url?");
    } finally {

        if (reader != null) {
            try {
                reader.close();

            } catch (IOException e) {
                throw new XinException("xin.error.url", "url:" + url + ", reader");
            }
        }

        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                throw new XinException("xin.error.url", "url:" + url + ", ?");
            }
        }

        // 
        quietClose(conn);
    }
}

From source file:de.unidue.stud.sehawagn.oidcclient.SimpleOIDCClient.java

public static void trustEverybody(HttpsURLConnection connection) {
    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }/*from w  w  w .j a  v a2 s  . com*/
    };

    // Install the all-trusting trust manager and host name verifier
    SSLContext sc = getTrustEverybodySSLContext();

    if (connection == null) {
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    } else {
        connection.setSSLSocketFactory(sc.getSocketFactory());
        connection.setHostnameVerifier(allHostsValid);
    }
}

From source file:com.cloudera.nav.sdk.client.writer.MetadataWriterFactory.java

private HttpURLConnection openConnection(URL url) throws IOException {
    if (isSSL) {/*from   w  ww .  j  a v a  2  s .  c  om*/
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setHostnameVerifier(hostnameVerifier);
        conn.setSSLSocketFactory(sslContext.getSocketFactory());
        return conn;
    } else {
        return (HttpURLConnection) url.openConnection();
    }
}

From source file:dk.netarkivet.common.distribute.HTTPSRemoteFileRegistry.java

/**
 * Open a connection to an URL in this registry. Thus opens SSL connections using the certificate above.
 *
 * @param url The URL to open connection to.
 * @return an open connection to the given url
 * @throws IOException If unable to open connection to the URL
 * @throws IOFailure If the connection is not a secure connection
 *//*  w  ww  .  java 2 s . c o  m*/
@Override
protected URLConnection openConnection(URL url) throws IOException {
    URLConnection connection = url.openConnection();
    if (!(connection instanceof HttpsURLConnection)) {
        throw new IOFailure("Not a secure URL to remote file: " + url);
    }
    HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
    httpsConnection.setSSLSocketFactory(sslContext.getSocketFactory());
    httpsConnection.setHostnameVerifier(ACCEPTING_HOSTNAME_VERIFIER);
    return httpsConnection;
}

From source file:org.freshrss.easyrss.network.NetworkClient.java

private HttpURLConnection makeConnection(final String url) throws MalformedURLException, IOException {
    final HttpURLConnection httpURLConnection = (HttpURLConnection) (new URL(url).openConnection());
    httpURLConnection.setConnectTimeout(40 * 1000);
    httpURLConnection.setReadTimeout(30 * 1000);
    if (url.toLowerCase(Locale.US).startsWith("https://")) {
        final HttpsURLConnection httpsURLConnection = (HttpsURLConnection) httpURLConnection;
        httpsURLConnection.setSSLSocketFactory(this.sslSocketFactory);
    }/*from  ww  w . j a v  a  2  s .  c o  m*/
    return httpURLConnection;
}

From source file:com.gson.util.HttpKit.java

/**
 * ?http?//from ww  w. j  a  v a 2 s  .  co  m
 * @param url
 * @param method
 * @return
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws KeyManagementException
 */
private static HttpsURLConnection initHttps(String url, String method, Map<String, String> headers)
        throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
    TrustManager[] tm = { new MyX509TrustManager() };
    System.setProperty("https.protocols", "SSLv3");
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
    sslContext.init(null, tm, new java.security.SecureRandom());
    // SSLContextSSLSocketFactory  
    SSLSocketFactory ssf = sslContext.getSocketFactory();
    URL _url = new URL(url);
    HttpsURLConnection http = (HttpsURLConnection) _url.openConnection();
    // ??
    http.setHostnameVerifier(new HttpKit().new TrustAnyHostnameVerifier());
    // 
    http.setConnectTimeout(25000);
    // ? --??
    http.setReadTimeout(25000);
    http.setRequestMethod(method);
    http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    http.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
    if (null != headers && !headers.isEmpty()) {
        for (Entry<String, String> entry : headers.entrySet()) {
            http.setRequestProperty(entry.getKey(), entry.getValue());
        }
    }
    http.setSSLSocketFactory(ssf);
    http.setDoOutput(true);
    http.setDoInput(true);
    http.connect();
    return http;
}

From source file:com.hichengdai.qlqq.front.util.HttpKit.java

/**
 * ?http?/*  ww w  . j  ava 2 s  . com*/
 * 
 * @param url
 * @param method
 * @return
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws KeyManagementException
 */
private static HttpsURLConnection initHttps(String url, String method, Map<String, String> headers)
        throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
    TrustManager[] tm = { new MyX509TrustManager() };
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
    sslContext.init(null, tm, new java.security.SecureRandom());
    // SSLContextSSLSocketFactory
    SSLSocketFactory ssf = sslContext.getSocketFactory();
    URL _url = new URL(url);
    HttpsURLConnection http = (HttpsURLConnection) _url.openConnection();
    // ??
    http.setHostnameVerifier(new HttpKit().new TrustAnyHostnameVerifier());
    // 
    http.setConnectTimeout(25000);
    // ? --??
    http.setReadTimeout(25000);
    http.setRequestMethod(method);
    http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    http.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
    if (null != headers && !headers.isEmpty()) {
        for (Entry<String, String> entry : headers.entrySet()) {
            http.setRequestProperty(entry.getKey(), entry.getValue());
        }
    }
    http.setSSLSocketFactory(ssf);
    http.setDoOutput(true);
    http.setDoInput(true);
    http.connect();
    return http;
}

From source file:crossbear.convergence.ConvergenceConnector.java

/**
 * Contact a ConvergenceNotary and ask it for all information about certificate observations it has made on a specific host.
 * /* w  ww  .  j a va 2  s . c o  m*/
 * Please note: Contacting a ConvergenceNotary is possible with and without sending the fingerprint of the observed certificate. In both cases the Notary will send a list of
 * ConvergenceCertificateObservations. The problem is that if no fingerprint is sent or the fingerprint matches the last certificate that the Notary observed for the host, the Notary will just
 * read the list of ConvergenceCertificateObservations from its database. It will not contact the server to see if it the certificate is still the one it uses. The problem with that is that with
 * this algorithm Convergence usually makes only one certificate observation per server. When asked for that server a Notary will therefore reply "I saw that certificate last July". Since
 * Crossbear requires statements like "I saw this certificate since last July" it will send a fake-fingerprint to the Convergence Notaries. This compels the Notary to query the server for
 * its current certificate. After that the Notary will update its database and will then send the updated list of ConvergenceCertificateObservations to Crossbear.
 * 
 * @param notary
 *            The notary to contact
 * @param hostPort
 *            The Hostname and port of the server on which the information about the certificate observations is desired.
 * @return The Response-String that the Notary sent as an answer. It will contain a JSON-encoded list of ConvergenceCertificateObservations
 * @throws IOException
 * @throws KeyManagementException
 * @throws NoSuchAlgorithmException
 */
private static String contactNotary(ConvergenceNotary notary, String hostPort)
        throws IOException, KeyManagementException, NoSuchAlgorithmException {

    // Construct a fake fingerprint to send to the Notary (currently the Hex-String representation of "ConvergenceIsGreat:)")
    String data = "fingerprint=43:6F:6E:76:65:72:67:65:6E:63:65:49:73:47:72:65:61:74:3A:29";

    // Build the url to connect to based on the Notary and the certificate's host
    URL url = new URL("https://" + notary.getHostPort() + "/target/" + hostPort.replace(":", "+"));

    // Open a HttpsURLConnection for that url
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

    /*
     * Set a TrustManager on that connection that forces the use of the Notary's certificate. If the Notary sends any certificate that differs from the one that it is supposed to have (according
     * to the ConvergenceNotaries-table) an Exception will be thrown. This protects against Man-in-the-middle attacks placed between the Crossbear server and the Notary.
     */
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null,
            new TrustManager[] {
                    new TrustSingleCertificateTM(Message.hexStringToByteArray(notary.getCertSHA256Hash())) },
            new java.security.SecureRandom());
    conn.setSSLSocketFactory(sc.getSocketFactory());

    // Set the timeout during which the Notary has to reply
    conn.setConnectTimeout(3000);

    // POST the fake fingerprint to the Notary
    conn.setDoOutput(true);
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();

    // Get the Notary's response. Since Convergence replies with a 409-error if it has never observed a certificate conn.getInputStream() will be null. The way to get the Notarys reply in that case is to use conn.getErrorStream().
    InputStream is;
    if (conn.getResponseCode() >= 400) {
        is = conn.getErrorStream();

    } else {
        // This line should never be executed since we send a fake fingerprint that should never belong to an actually observed certificate. But who knows ...
        is = conn.getInputStream();
    }

    // Read the Notary's reply and store it
    String response = Message.inputStreamToString(is);

    // Close all opened streams
    wr.close();

    // Return the Notary's reply
    return response;

}

From source file:net.minder.KnoxWebHdfsJavaClientExamplesTest.java

private HttpsURLConnection createHttpUrlConnection(URL url) throws Exception {
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setHostnameVerifier(new TrustAllHosts());
    conn.setSSLSocketFactory(TrustAllCerts.createInsecureSslContext().getSocketFactory());
    conn.setInstanceFollowRedirects(false);
    String credentials = TEST_USERNAME + ":" + TEST_PASSWORD;
    conn.setRequestProperty("Authorization",
            "Basic " + DatatypeConverter.printBase64Binary(credentials.getBytes()));
    return conn;/*from  ww w . j  av a 2s  .c o  m*/
}

From source file:com.glaf.core.util.http.HttpUtils.java

/**
 * ?https?/*from  www  .  j  av  a2s  .c  om*/
 * 
 * @param requestUrl
 *            ?
 * @param method
 *            ?GET?POST
 * @param content
 *            ???
 * @return
 */
public static String doRequest(String requestUrl, String method, String content, boolean isSSL) {
    log.debug("requestUrl:" + requestUrl);
    HttpsURLConnection conn = null;
    InputStream inputStream = null;
    BufferedReader bufferedReader = null;
    InputStreamReader inputStreamReader = null;
    StringBuffer buffer = new StringBuffer();
    try {
        URL url = new URL(requestUrl);
        conn = (HttpsURLConnection) url.openConnection();
        if (isSSL) {
            // SSLContext??
            TrustManager[] tm = { new MyX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // SSLContextSSLSocketFactory
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            conn.setSSLSocketFactory(ssf);
        }
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        // ?GET/POST
        conn.setRequestMethod(method);
        if ("GET".equalsIgnoreCase(method)) {
            conn.connect();
        }

        // ????
        if (StringUtils.isNotEmpty(content)) {
            OutputStream outputStream = conn.getOutputStream();
            // ????
            outputStream.write(content.getBytes("UTF-8"));
            outputStream.flush();
            outputStream.close();
        }

        // ???
        inputStream = conn.getInputStream();
        inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
        bufferedReader = new BufferedReader(inputStreamReader);

        String str = null;
        while ((str = bufferedReader.readLine()) != null) {
            buffer.append(str);
        }

        log.debug("response:" + buffer.toString());

    } catch (ConnectException ce) {
        ce.printStackTrace();
        log.error(" http server connection timed out.");
    } catch (Exception ex) {
        ex.printStackTrace();
        log.error("http request error:{}", ex);
    } finally {
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(bufferedReader);
        IOUtils.closeQuietly(inputStreamReader);
        if (conn != null) {
            conn.disconnect();
        }
    }
    return buffer.toString();
}