Example usage for javax.net.ssl HttpsURLConnection connect

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

Introduction

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

Prototype

public abstract void connect() throws IOException;

Source Link

Document

Opens a communications link to the resource referenced by this URL, if such a connection has not already been established.

Usage

From source file:com.yahoo.athenz.example.http.tls.client.HttpTLSClient.java

public static void main(String[] args) {

    // parse our command line to retrieve required input

    CommandLine cmd = parseCommandLine(args);

    final String url = cmd.getOptionValue("url");
    final String keyPath = cmd.getOptionValue("key");
    final String certPath = cmd.getOptionValue("cert");
    final String trustStorePath = cmd.getOptionValue("trustStorePath");
    final String trustStorePassword = cmd.getOptionValue("trustStorePassword");

    // we are going to setup our service private key and
    // certificate into a ssl context that we can use with
    // our http client

    try {//from  w ww  .  java 2s . c o m
        KeyRefresher keyRefresher = Utils.generateKeyRefresher(trustStorePath, trustStorePassword, certPath,
                keyPath);
        SSLContext sslContext = Utils.buildSSLContext(keyRefresher.getKeyManagerProxy(),
                keyRefresher.getTrustManagerProxy());

        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
        HttpsURLConnection con = (HttpsURLConnection) new URL(url).openConnection();
        con.setReadTimeout(15000);
        con.setDoOutput(true);
        con.connect();

        try (BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            System.out.println("Data output: " + sb.toString());
        }

    } catch (Exception ex) {
        System.out.println("Exception: " + ex.getMessage());
        ex.printStackTrace();
        System.exit(1);
    }
}

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

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

From source file:com.clearcenter.mobile_demo.mdRest.java

static private StringBuffer ProcessRequest(HttpsURLConnection http) throws IOException {
    http.connect();

    Log.d(TAG, "Result code: " + http.getResponseCode() + ", content type: " + http.getContentType()
            + ", content length: " + http.getContentLength());

    // Read response, 8K buffer
    BufferedReader buffer = new BufferedReader(new InputStreamReader(http.getInputStream()), 8192);

    String data;/*from  ww w.j  a  v a2s  . co  m*/
    StringBuffer response = new StringBuffer();
    while ((data = buffer.readLine()) != null)
        response.append(data);

    Log.d(TAG, "Response buffer length: " + response.length());

    buffer.close();
    http.disconnect();

    return response;
}

From source file:Main.java

private static String getData(String target, String method, String token) {
    try {/*from www . j av a2s .  com*/
        URL url = new URL(target);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

        if (!TextUtils.isEmpty(token))
            conn.setRequestProperty("Authorization", token);

        conn.setRequestMethod(method);
        conn.connect();

        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line, data = "";
        while ((line = in.readLine()) != null)
            data += line;
        in.close();

        return data;
    } catch (IOException ignored) {
        ignored.printStackTrace();
    }

    return null;
}

From source file:Main.java

private static String getData(String target, String method, String token) {
    try {//from  w  w w . j  a v a2 s. com
        URL url = new URL(target);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

        if (!TextUtils.isEmpty(token)) {
            conn.setRequestProperty("Authorization", token);
        }

        conn.setRequestMethod(method);
        conn.connect();

        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line, data = "";
        while ((line = in.readLine()) != null) {
            data += line;
        }
        in.close();

        return data;
    } catch (IOException ignored) {
        ignored.printStackTrace();
    }

    return null;
}

From source file:org.apache.hadoop.hdfsproxy.ProxyUtil.java

static void checkServerCertsExpirationDays(Configuration conf, String hostname, int port) throws IOException {
    setupSslProps(conf);/*from   ww w  .j  a v a2s . co  m*/
    HttpsURLConnection connection = null;
    connection = openConnection(hostname, port, null);
    connection.connect();
    X509Certificate[] serverCerts = (X509Certificate[]) connection.getServerCertificates();
    Date curDate = new Date();
    long curTime = curDate.getTime();
    if (serverCerts != null) {
        for (X509Certificate cert : serverCerts) {
            StringBuffer sb = new StringBuffer();
            sb.append("\n Server certificate Subject Name: " + cert.getSubjectX500Principal().getName());
            Date expDate = cert.getNotAfter();
            long expTime = expDate.getTime();
            int dayOffSet = (int) ((expTime - curTime) / MM_SECONDS_PER_DAY);
            sb.append(" have " + dayOffSet + " days to expire");
            if (dayOffSet < CERT_EXPIRATION_WARNING_THRESHOLD)
                LOG.warn(sb.toString());
            else
                LOG.info(sb.toString());
        }
    } else {
        LOG.info("\n No Server certs was found");
    }

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

From source file:org.apache.hadoop.hdfsproxy.ProxyUtil.java

static boolean sendCommand(Configuration conf, String path) throws IOException {
    setupSslProps(conf);/*from  w w w  . ja  va 2  s .  co  m*/
    int sslPort = getSslAddr(conf).getPort();
    int err = 0;
    StringBuilder b = new StringBuilder();

    HostsFileReader hostsReader = new HostsFileReader(conf.get("hdfsproxy.hosts", "hdfsproxy-hosts"), "");
    Set<String> hostsList = hostsReader.getHosts();
    for (String hostname : hostsList) {
        HttpsURLConnection connection = null;
        try {
            connection = openConnection(hostname, sslPort, path);
            connection.connect();
            if (LOG.isDebugEnabled()) {
                StringBuffer sb = new StringBuffer();
                X509Certificate[] clientCerts = (X509Certificate[]) connection.getLocalCertificates();
                if (clientCerts != null) {
                    for (X509Certificate cert : clientCerts)
                        sb.append("\n Client certificate Subject Name is "
                                + cert.getSubjectX500Principal().getName());
                } else {
                    sb.append("\n No client certificates were found");
                }
                X509Certificate[] serverCerts = (X509Certificate[]) connection.getServerCertificates();
                if (serverCerts != null) {
                    for (X509Certificate cert : serverCerts)
                        sb.append("\n Server certificate Subject Name is "
                                + cert.getSubjectX500Principal().getName());
                } else {
                    sb.append("\n No server certificates were found");
                }
                LOG.debug(sb.toString());
            }
            if (connection.getResponseCode() != HttpServletResponse.SC_OK) {
                b.append("\n\t" + hostname + ": " + connection.getResponseCode() + " "
                        + connection.getResponseMessage());
                err++;
            }
        } catch (IOException e) {
            b.append("\n\t" + hostname + ": " + e.getLocalizedMessage());
            if (LOG.isDebugEnabled())
                LOG.debug("Exception happend for host " + hostname, e);
            err++;
        } finally {
            if (connection != null)
                connection.disconnect();
        }
    }
    if (err > 0) {
        System.err.print("Command failed on the following " + err + " host" + (err == 1 ? ":" : "s:")
                + b.toString() + "\n");
        return false;
    }
    return true;
}

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

public static String doGet(String url) {
    InputStream in = null;//from w w  w  .j  a  v a2  s .co 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();
}

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

public static ByteArrayOutputStream doGetImg(String url, String cookieStr) {
    InputStream in = null;/* ww  w .j a  va  2 s .  c o  m*/
    ByteArrayOutputStream outStream = null;
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());

        URL console = new URL(url);
        HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
        conn.setRequestProperty("Cookie", cookieStr);
        conn.setSSLSocketFactory(sc.getSocketFactory());
        conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
        conn.connect();
        in = conn.getInputStream();
        outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = in.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        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 {
            in.close();
        } catch (Exception e) {
        }
    }
    return outStream;
}

From source file:au.id.micolous.frogjump.Util.java

public static void updateCheck(final Activity activity) {
    (new AsyncTask<Void, Void, Boolean>() {
        @Override/*from w ww .  j a  va2s. co m*/
        protected Boolean doInBackground(Void... voids) {
            try {
                String my_version = Integer.toString(getVersionCode());
                URL url = new URL("https://micolous.github.io/frogjump/version.json");
                HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setDoInput(true);
                conn.setReadTimeout(10000);
                conn.setConnectTimeout(15000);
                conn.connect();

                int responseCode = conn.getResponseCode();
                if (responseCode == 200) {
                    InputStream is = conn.getInputStream();
                    byte[] buffer = new byte[1024];
                    if (is.read(buffer) == 0) {
                        Log.i(TAG, "Error reading update file, 0 bytes");
                        return false;
                    }
                    JSONObject root = (JSONObject) new JSONTokener(new String(buffer, "US-ASCII")).nextValue();

                    if (root.has(my_version)) {
                        if (root.getBoolean(my_version)) {
                            // Definitely needs update.
                            Log.i(TAG, "New version required, explicit flag.");
                            return true;
                        }
                    } else {
                        // unlisted version, assume it is old.
                        Log.i(TAG, "New version required, not in list.");
                        return true;
                    }

                }
            } catch (Exception ex) {
                Log.e(TAG, "Error getting update info", ex);
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean needsUpdate) {
            if (needsUpdate)
                newVersionAlert(activity);
        }
    }).execute();
}