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:homenetapp.HomeNetAppGui.java

private void checkClientCert() {
    try {//ww  w .  jav  a  2s  . c om
        URL url = new URL("https://" + homenetapp.clientServer + "/");
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.connect();
        Certificate[] certs = conn.getServerCertificates();

        //System.out.println("Cert Chain Length: "+certs.length);

        Certificate c = certs[0];
        X509Certificate xc = (X509Certificate) c;

        String[] from = homenetapp.splitTokens(xc.getIssuerX500Principal().getName(), "=, ");
        String[] to = homenetapp.splitTokens(xc.getSubjectX500Principal().getName(), "=, ");

        certPropertiesLabel.setText("<html>Issued by: " + from[1] + "<br>For: " + to[1] + "<br>Expires: "
                + xc.getNotAfter() + "</html>");

        System.out.println("Cert: " + c.getType());

        System.out.println("Not After: " + xc.getNotAfter());
        System.out.println("Subject DN: " + xc.getSubjectX500Principal());
        System.out.println("Issuer DN: " + xc.getIssuerX500Principal());
        System.out.println("getSigAlgName: " + xc.getSigAlgName());

    } catch (Exception e) {
        certPropertiesLabel.setText("Failed to load certficate");
    }

}

From source file:com.gmt2001.TwitchAPIv3.java

@SuppressWarnings("UseSpecificCatch")
private JSONObject GetData(request_type type, String url, String post, String oauth, boolean isJson) {
    JSONObject j = new JSONObject("{}");
    InputStream i = null;// w w w .j  a v a2 s .c  o  m
    String rawcontent = "";

    try {
        if (url.contains("?")) {
            url += "&utcnow=" + System.currentTimeMillis();
        } else {
            url += "?utcnow=" + System.currentTimeMillis();
        }

        URL u = new URL(url);
        HttpsURLConnection c = (HttpsURLConnection) u.openConnection();

        c.addRequestProperty("Accept", header_accept);

        if (isJson) {
            c.addRequestProperty("Content-Type", "application/json");
        } else {
            c.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        }

        if (!clientid.isEmpty()) {
            c.addRequestProperty("Client-ID", clientid);
        }

        if (!oauth.isEmpty()) {
            c.addRequestProperty("Authorization", "OAuth " + oauth);
        }

        c.setRequestMethod(type.name());

        c.setUseCaches(false);
        c.setDefaultUseCaches(false);
        c.setConnectTimeout(timeout);
        c.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015");

        if (!post.isEmpty()) {
            c.setDoOutput(true);
        }

        c.connect();

        if (!post.isEmpty()) {
            try (OutputStream o = c.getOutputStream()) {
                IOUtils.write(post, o);
            }
        }

        String content;

        if (c.getResponseCode() == 200) {
            i = c.getInputStream();
        } else {
            i = c.getErrorStream();
        }

        if (c.getResponseCode() == 204 || i == null) {
            content = "{}";
        } else {
            content = IOUtils.toString(i, c.getContentEncoding());
        }

        rawcontent = content;

        j = new JSONObject(content);
        j.put("_success", true);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", c.getResponseCode());
        j.put("_exception", "");
        j.put("_exceptionMessage", "");
        j.put("_content", content);
    } catch (JSONException ex) {
        if (ex.getMessage().contains("A JSONObject text must begin with")) {
            j = new JSONObject("{}");
            j.put("_success", true);
            j.put("_type", type.name());
            j.put("_url", url);
            j.put("_post", post);
            j.put("_http", 0);
            j.put("_exception", "");
            j.put("_exceptionMessage", "");
            j.put("_content", rawcontent);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    } catch (NullPointerException ex) {
        com.gmt2001.Console.err.printStackTrace(ex);
    } catch (MalformedURLException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_exception", "MalformedURLException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");
        com.gmt2001.Console.err.logStackTrace(ex);
    } catch (SocketTimeoutException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_exception", "SocketTimeoutException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");
        com.gmt2001.Console.err.logStackTrace(ex);
    } catch (IOException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_exception", "IOException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");
        com.gmt2001.Console.err.logStackTrace(ex);
    } catch (Exception ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_exception", "Exception [" + ex.getClass().getName() + "]");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");
        com.gmt2001.Console.err.logStackTrace(ex);
    }

    if (i != null) {
        try {
            i.close();
        } catch (IOException ex) {
            j.put("_success", false);
            j.put("_type", type.name());
            j.put("_url", url);
            j.put("_post", post);
            j.put("_http", 0);
            j.put("_exception", "IOException");
            j.put("_exceptionMessage", ex.getMessage());
            j.put("_content", "");
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    }

    return j;
}

From source file:com.gmt2001.TwitchAPIv5.java

@SuppressWarnings("UseSpecificCatch")
private JSONObject GetData(request_type type, String url, String post, String oauth, boolean isJson) {
    JSONObject j = new JSONObject("{}");
    InputStream i = null;//from   ww  w . j av  a 2s  . c o m
    String content = "";

    try {
        URL u = new URL(url);
        HttpsURLConnection c = (HttpsURLConnection) u.openConnection();
        c.addRequestProperty("Accept", header_accept);
        c.addRequestProperty("Content-Type", isJson ? "application/json" : "application/x-www-form-urlencoded");

        if (!clientid.isEmpty()) {
            c.addRequestProperty("Client-ID", clientid);
        }

        if (!oauth.isEmpty()) {
            c.addRequestProperty("Authorization", "OAuth " + oauth);
        } else {
            if (!this.oauth.isEmpty()) {
                c.addRequestProperty("Authorization", "OAuth " + oauth);
            }
        }

        c.setRequestMethod(type.name());
        c.setConnectTimeout(timeout);
        c.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015");

        if (!post.isEmpty()) {
            c.setDoOutput(true);
        }

        c.connect();

        if (!post.isEmpty()) {
            try (OutputStream o = c.getOutputStream()) {
                IOUtils.write(post, o);
            }
        }

        if (c.getResponseCode() == 200) {
            i = c.getInputStream();
        } else {
            i = c.getErrorStream();
        }

        if (c.getResponseCode() == 204 || i == null) {
            content = "{}";
        } else {
            // default to UTF-8, it'll probably be the best bet if there's
            // no charset specified.
            String charset = "utf-8";
            String ct = c.getContentType();
            if (ct != null) {
                String[] cts = ct.split(" *; *");
                for (int idx = 1; idx < cts.length; ++idx) {
                    String[] val = cts[idx].split("=", 2);
                    if (val[0] == "charset" && val.length > 1) {
                        charset = val[1];
                    }
                }
            }

            if ("gzip".equals(c.getContentEncoding())) {
                i = new GZIPInputStream(i);
            }

            content = IOUtils.toString(i, charset);
        }

        j = new JSONObject(content);
        fillJSONObject(j, true, type.name(), post, url, c.getResponseCode(), "", "", content);
    } catch (Exception ex) {
        Throwable rootCause = ex;
        while (rootCause.getCause() != null && rootCause.getCause() != rootCause) {
            rootCause = rootCause.getCause();
        }

        fillJSONObject(j, false, type.name(), post, url, 0, ex.getClass().getSimpleName(), ex.getMessage(),
                content);
        com.gmt2001.Console.debug
                .println("Failed to get data [" + ex.getClass().getSimpleName() + "]: " + ex.getMessage());
    } finally {
        if (i != null) {
            try {
                i.close();
            } catch (IOException ex) {
                fillJSONObject(j, false, type.name(), post, url, 0, "IOException", ex.getMessage(), content);
                com.gmt2001.Console.err.println("IOException: " + ex.getMessage());
            }
        }
    }

    return j;
}

From source file:com.photon.phresco.framework.rest.api.ConfigurationService.java

/**
 * Checks if is connection alive.//  w  ww. ja  v  a  2s.  c  o  m
 *
 * @param protocol the protocol
 * @param host the host
 * @param port the port
 * @return true, if is connection alive
 */
public boolean isConnectionAlive(String protocol, String host, int port) {
    boolean isAlive = true;
    try {
        URL url = new URL(protocol, host, port, "");
        URLConnection connection = url.openConnection();
        if (protocol.equalsIgnoreCase("http")) {
            HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
            httpConnection.connect();
        } else {
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                }

                public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                }
            } };

            SSLContext sc = SSLContext.getInstance(SSL);
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
            https.connect();

        }

    } catch (Exception e) {
        isAlive = false;
    }

    return isAlive;
}

From source file:com.example.android.networkconnect.MainActivity.java

private String https_test(String urlString) throws IOException {

    String token = "";
    URL url = new URL(urlString);

    Log.i(TAG, "Protocol: " + url.getProtocol().toString());

    // if (url.getProtocol().toLowerCase().equals("https")) {
    trustAllHosts();/*from  w  w  w.j  a  v  a  2  s  .  c om*/

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

    conn.setReadTimeout(20000 /* milliseconds */);
    conn.setConnectTimeout(25000 /* milliseconds */);
    // conn.setRequestMethod("GET");
    conn.setDoInput(true);
    conn.setDoOutput(true);

    conn.setChunkedStreamingMode(0);

    conn.setRequestProperty("User-Agent", "e-venement-app/");

    // OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
    //writer.getEncoding();
    //writer.write("&signin[username]=antoine");
    //writer.write("&signin[password]=android2015@");
    //writer.write("?control[id]=");
    //writer.write("&control[ticket_id]=2222");
    //writer.write("&control[checkpoint_id]=1");
    //  writer.write("&control[comment]=");

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); //On cre la liste qui contiendra tous nos paramtres

    //Et on y rajoute nos paramtres
    nameValuePairs.add(new BasicNameValuePair("signin[username]", "antoine"));
    nameValuePairs.add(new BasicNameValuePair("signin[password]", "android2015@"));
    //nameValuePairs.add(new BasicNameValuePair("control[id]", ""));
    //nameValuePairs.add(new BasicNameValuePair("control[ticket_id]", "2222"));
    //nameValuePairs.add(new BasicNameValuePair("control[checkpoint_id]", "1"));
    //nameValuePairs.add(new BasicNameValuePair("control[comment]", ""));

    OutputStream os = conn.getOutputStream();
    BufferedWriter writer2 = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
    writer2.write(getQuery(nameValuePairs));
    writer2.flush();
    //writer2.close();
    //os.close();

    // conn.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    //writer.write("&signin[_csrf_token]="+CSRFTOKEN);
    //writer.flush();

    conn.connect();

    String headerName = null;

    for (int i = 1; (headerName = conn.getHeaderFieldKey(i)) != null; i++) {
        //data=data+"Header Nme : " + headerName;
        //data=data+conn.getHeaderField(i);
        // Log.i (TAG,headerName);
        Log.i(TAG, headerName + ": " + conn.getHeaderField(i));

    }

    int responseCode = conn.getResponseCode();

    if (responseCode == conn.HTTP_OK) {
        final String COOKIES_HEADER = "Set-Cookie";
        cookie = conn.getHeaderField(COOKIES_HEADER);
    }

    if (conn.getInputStream() != null) {

        // token =getStringFromInputStream(conn.getInputStream());
        Log.i(TAG, readIt(conn.getInputStream(), 15000));
        token = readIt(conn.getInputStream(), 15000);
        Log.i(TAG, getStringFromInputStream(conn.getInputStream()));
        //data=readIt(conn.getInputStream(),7500);
        //Log.i(TAG,token);
        //token=readIt(conn.getInputStream(),7500);
    }
    //conn.connect();
    // List<String> cookiesList = conn.getHeaderFields().get("Set-Cookie");

    // }
    //conn.disconnect();
    return token;
}

From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java

/** Return a HttpsURLConnection for a GET, using client certificate authentication to the url. The url should be EJBCA client protected https port, i.e. 8443
 * @param url the URL to connect to, i.e. https://localhost:8443/ejbca/adminweb/index.jsp
 *//*from   w  ww  .  ja v  a2 s . c  om*/
protected HttpURLConnection getHttpsURLConnection(String url) throws IOException, UnrecoverableKeyException,
        KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException {
    final HttpsURLConnection con;
    URL u = new URL(url);
    con = (HttpsURLConnection) u.openConnection();
    con.setHostnameVerifier(new SimpleVerifier());
    con.setSSLSocketFactory(getSSLFactory());
    con.setRequestMethod("GET");
    con.getDoOutput();
    con.connect();
    return con;
}

From source file:com.kimbrelk.da.oauth2.OAuth2.java

protected final JSONObject requestJSON(Verb verb, String url, String postData) {
    try {/*from  w w  w  .j a va2s.c om*/
        mLog.append("SEND:\n");
        HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
        connection.setRequestProperty("User-Agent", mUserAgent);
        connection.setRequestProperty("dA-minor-version", "" + VERSION.getMinor());
        connection.setReadTimeout(30000);
        connection.setConnectTimeout(30000);
        mLog.append(verb.toString() + " ");
        mLog.append(url);
        mLog.append("\n");
        connection.setRequestMethod(verb.toString());
        if (verb == Verb.POST) {
            mLog.append(postData);
            mLog.append("\n");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            //connection.setRequestProperty("Authorization", "Basic " + base64(CLIENT_ID + ":" + loadLast()));
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Content-Length", "" + postData.length());
            connection.connect();
            OutputStream os = connection.getOutputStream();
            os.write(postData.getBytes());
            os.flush();
        } else if (verb == Verb.GET) {
            connection.setDoOutput(false);
            connection.setDoInput(true);
            connection.connect();
        }
        mLog.append("\nRECV:\n");

        try {
            InputStream is = connection.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader in = new BufferedReader(isr);
            String line = "";
            String page = "";
            while ((line = in.readLine()) != null) {
                page += line;
            }
            mLog.append(page);
            mLog.append("\n\n");
            return new JSONObject(page);
        } catch (Exception e) {
            try {
                JSONObject json = new JSONObject();
                json.put("status", "error");
                try {
                    InputStream is = connection.getErrorStream();
                    InputStreamReader isr = new InputStreamReader(is);
                    BufferedReader in = new BufferedReader(isr);
                    String line = "";
                    String page = "";
                    while ((line = in.readLine()) != null) {
                        page += line;
                    }
                    mLog.append(page);
                    mLog.append("\n\n");
                    return new JSONObject(page);
                } catch (Exception err) {

                }
                try {
                    if (connection.getResponseCode() == 403 || connection.getResponseCode() == 429) {
                        json.put("error_description", RespError.RATE_LIMIT.getDescription());
                        json.put("error", RespError.RATE_LIMIT.getType());
                        return json;
                    }
                } catch (IOException er) {

                }
                String str = "";
                str += "URL: " + url.split("[?]+")[0] + "\n";
                //str += "POST Data: " + postData + "\n";
                str += "\n";
                for (int a = 0; a < connection.getHeaderFields().size() - 1; a++) {
                    str += connection.getHeaderFieldKey(a) + ": " + connection.getHeaderField(a) + "\n";
                }
                json.put("error_description", str);
                json.put("error", RespError.REQUEST_FAILED.getType());
                return json;
            } catch (Exception er) {
                throw e;
            }
        } finally {
            connection.disconnect();
        }
    } catch (Exception e) {
        try {
            e.printStackTrace();
            JSONObject json = new JSONObject();
            json.put("status", "error");
            json.put("error", RespError.REQUEST_FAILED.getType());
            json.put("error_description", RespError.REQUEST_FAILED.getDescription() + " : " + e);
            return json;
        } catch (JSONException er) {
            er.printStackTrace();
            return null;
        }
    }
}

From source file:com.codename1.impl.android.AndroidImplementation.java

@Override
public String[] getSSLCertificates(Object connection, String url) throws IOException {
    if (connection instanceof HttpsURLConnection) {
        HttpsURLConnection conn = (HttpsURLConnection) connection;

        try {//w ww  . j  ava2 s .  co  m
            conn.connect();
            java.security.cert.Certificate[] certs = conn.getServerCertificates();
            String[] out = new String[certs.length];
            int i = 0;
            for (java.security.cert.Certificate cert : certs) {
                MessageDigest md = MessageDigest.getInstance("SHA1");
                md.update(cert.getEncoded());
                out[i++] = "SHA1:" + dumpHex(md.digest());
            }
            return out;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    return new String[0];

}