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.cloudbees.tftwoway.Client.java

public static void main(String[] args) throws Exception {
    URL url = new URL(SERVER_ADDRESS);
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

    SSLContext sslContext = createSSLContext();
    connection.setSSLSocketFactory(sslContext.getSocketFactory());

    connection.connect();/* www  .  ja v  a  2 s .  c  o  m*/

    int responseCode = connection.getResponseCode();
    String response = IOUtils.toString(connection.getInputStream(), connection.getContentEncoding());
    System.out.println(responseCode);
    System.out.println(response);
}

From source file:org.apache.hadoop.hbase.http.TestSSLHttpServer.java

private static String readOut(URL url) throws Exception {
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setSSLSocketFactory(clientSslFactory.createSSLSocketFactory());
    InputStream in = conn.getInputStream();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    IOUtils.copyBytes(in, out, 1024);//from w w  w. j  a  v  a 2 s.  c  om
    return out.toString();
}

From source file:org.thoughtcrime.ssl.pinning.util.PinningHelper.java

/**
 * Constructs an HttpsURLConnection that will validate HTTPS connections against a set of
 * specified pins.// w  ww .  java  2 s .  co m
 *
 * @param pins An array of encoded pins to match a seen certificate
 *             chain against. A pin is a hex-encoded hash of a X.509 certificate's
 *             SubjectPublicKeyInfo. A pin can be generated using the provided pin.py
 *             script: python ./tools/pin.py certificate_file.pem
 *
 */

public static HttpsURLConnection getPinnedHttpsURLConnection(Context context, String[] pins, URL url)
        throws IOException {
    try {
        if (!url.getProtocol().equals("https")) {
            throw new IllegalArgumentException("Attempt to construct pinned non-https connection!");
        }

        TrustManager[] trustManagers = new TrustManager[1];
        trustManagers[0] = new PinningTrustManager(SystemKeyStore.getInstance(context), pins, 0);

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustManagers, null);

        HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
        urlConnection.setSSLSocketFactory(sslContext.getSocketFactory());

        return urlConnection;
    } catch (NoSuchAlgorithmException nsae) {
        throw new AssertionError(nsae);
    } catch (KeyManagementException e) {
        throw new AssertionError(e);
    }
}

From source file:org.wso2.carbon.identity.application.authentication.endpoint.util.AuthContextAPIClient.java

/**
 * Send mutual ssl https post request and return data
 *
 * @param backendURL   URL of the service
 * @return Received data/*  ww  w  . ja  v a 2s  . c o  m*/
 * @throws IOException
 */
public static String getContextProperties(String backendURL) {
    InputStream inputStream = null;
    BufferedReader reader = null;
    String response = null;
    URL url = null;

    try {
        url = new URL(backendURL);
        HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
        httpsURLConnection.setSSLSocketFactory(MutualSSLManager.getSslSocketFactory());
        httpsURLConnection.setDoOutput(true);
        httpsURLConnection.setDoInput(true);
        httpsURLConnection.setRequestMethod(HTTP_METHOD_GET);

        httpsURLConnection.setRequestProperty(MutualSSLManager.getUsernameHeaderName(),
                MutualSSLManager.getCarbonLogin());

        inputStream = httpsURLConnection.getInputStream();
        reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
        StringBuilder builder = new StringBuilder();
        String line;

        while (StringUtils.isNotEmpty(line = reader.readLine())) {
            builder.append(line);
        }
        response = builder.toString();
    } catch (IOException e) {
        log.error("Sending " + HTTP_METHOD_GET + " request to URL : " + url + "failed.", e);
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }

        } catch (IOException e) {
            log.error("Closing stream for " + url + " failed", e);
        }
    }
    return response;
}

From source file:Main.java

private static HttpsURLConnection setSSLSocketFactory(HttpsURLConnection connection)
        throws KeyManagementException, NoSuchAlgorithmException {
    SSLContext sc;//  ww w .j  av  a  2 s. c  o  m
    sc = SSLContext.getInstance("TLS");
    sc.init(null, null, new java.security.SecureRandom());
    connection.setSSLSocketFactory(sc.getSocketFactory());
    return connection;
}

From source file:org.apache.hadoop.hdfs.web.URLConnectionFactory.java

/**
 * Create a new ConnectionConfigurator for SSL connections
 *//* www  . j  av  a2  s. c o  m*/
private static ConnectionConfigurator newSslConnConfigurator(final int timeout, Configuration conf)
        throws IOException, GeneralSecurityException {
    final SSLFactory factory;
    final SSLSocketFactory sf;
    final HostnameVerifier hv;

    factory = new SSLFactory(SSLFactory.Mode.CLIENT, conf);
    factory.init();
    sf = factory.createSSLSocketFactory();
    hv = factory.getHostnameVerifier();

    return new ConnectionConfigurator() {
        @Override
        public HttpURLConnection configure(HttpURLConnection conn) throws IOException {
            if (conn instanceof HttpsURLConnection) {
                HttpsURLConnection c = (HttpsURLConnection) conn;
                c.setSSLSocketFactory(sf);
                c.setHostnameVerifier(hv);
            }
            URLConnectionFactory.setTimeouts(conn, timeout);
            return conn;
        }
    };
}

From source file:com.ct855.util.HttpsClientUtil.java

public static String postUrl(String url, Map<String, String> params)
        throws IOException, NoSuchAlgorithmException, KeyManagementException, NoSuchProviderException {
    //SSLContext??
    TrustManager[] trustAllCerts = new TrustManager[] { new MyX509TrustManager() };
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
    sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

    //SSLContextSSLSocketFactory
    SSLSocketFactory ssf = sslContext.getSocketFactory();
    String data = "";
    for (String key : params.keySet()) {
        data += "&" + URLEncoder.encode(key, "UTF-8") + "=" + URLEncoder.encode(params.get(key), "UTF-8");
    }//w  w w  . j a  v a 2 s .  c o m
    data = data.substring(1);

    System.out.println("postUrl=>data:" + data);
    URL aURL = new java.net.URL(url);
    HttpsURLConnection aConnection = (HttpsURLConnection) aURL.openConnection();
    aConnection.setSSLSocketFactory(ssf);
    aConnection.setDoOutput(true);
    aConnection.setDoInput(true);
    aConnection.setRequestMethod("POST");
    OutputStreamWriter streamToAuthorize = new java.io.OutputStreamWriter(aConnection.getOutputStream());
    streamToAuthorize.write(data);
    streamToAuthorize.flush();
    streamToAuthorize.close();
    InputStream resultStream = aConnection.getInputStream();
    BufferedReader aReader = new java.io.BufferedReader(new java.io.InputStreamReader(resultStream));
    StringBuffer aResponse = new StringBuffer();
    String aLine = aReader.readLine();
    while (aLine != null) {
        aResponse.append(aLine + "\n");
        aLine = aReader.readLine();
    }
    resultStream.close();
    return aResponse.toString();
}

From source file:och.util.NetUtil.java

public static HttpURLConnection setTrustAnyHttps(HttpURLConnection conn) {

    if (trustAllSocketFactory == null) {
        log.error("can't setTrustAnyHttps for " + conn);
        return conn;
    }//from   ww w  . j a va2s.  co  m

    if (conn instanceof HttpsURLConnection) {
        HttpsURLConnection https = (HttpsURLConnection) conn;
        https.setSSLSocketFactory(trustAllSocketFactory);
        https.setHostnameVerifier(allHostVerifier);
    }
    return conn;
}

From source file:org.apache.atlas.security.SecureClientUtils.java

private static ConnectionConfigurator newSslConnConfigurator(final int timeout, Configuration conf)
        throws IOException, GeneralSecurityException {
    final SSLFactory factory;
    final SSLSocketFactory sf;
    final HostnameVerifier hv;

    factory = new SSLFactory(SSLFactory.Mode.CLIENT, conf);
    factory.init();//from   w  w w  .ja  va  2  s . com
    sf = factory.createSSLSocketFactory();
    hv = factory.getHostnameVerifier();

    return new ConnectionConfigurator() {
        @Override
        public HttpURLConnection configure(HttpURLConnection conn) throws IOException {
            if (conn instanceof HttpsURLConnection) {
                HttpsURLConnection c = (HttpsURLConnection) conn;
                c.setSSLSocketFactory(sf);
                c.setHostnameVerifier(hv);
            }
            setTimeouts(conn, timeout);
            return conn;
        }
    };
}

From source file:com.camel.trainreserve.JDKHttpsClient.java

public static String doGet(String url) {
    InputStream in = null;/*from  www  . ja v a 2  s.c  o  m*/
    BufferedReader br = null;
    StringBuffer str_return = new StringBuffer();
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, new TrustManager[] { new DefaultTrustManager() }, new java.security.SecureRandom());
        URL console = new URL(url);
        HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
        conn.setSSLSocketFactory(sc.getSocketFactory());
        conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
        conn.connect();
        in = conn.getInputStream();
        br = new BufferedReader(new InputStreamReader(in));
        String line = null;
        while ((line = br.readLine()) != null) {
            str_return = str_return.append(line);
        }
        conn.disconnect();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        try {
            br.close();
            in.close();
        } catch (Exception e) {
        }
    }
    return str_return.toString();
}