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.hichengdai.qlqq.front.util.HttpKit.java

/**
 * ?http?/*from w  ww.  j  a v a  2 s. c o 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() };
    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:org.wso2.carbon.automation.test.utils.http.client.HttpsURLConnectionClient.java

public static HttpsResponse postWithBasicAuth(String uri, String requestQuery, String contentType,
        String userName, String password) throws IOException {
    if (uri.startsWith("https://")) {
        URL url = new URL(uri);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        String encode = new String(
                new org.apache.commons.codec.binary.Base64().encode((userName + ":" + password).getBytes()))
                        .replaceAll("\n", "");
        conn.setRequestProperty("Authorization", "Basic " + encode);
        conn.setDoOutput(true); // Triggers POST.
        conn.setRequestProperty("Content-Type", contentType);
        conn.setRequestProperty("charset", "utf-8");
        conn.setRequestProperty("Content-Length", "" + Integer.toString(requestQuery.getBytes().length));
        conn.setUseCaches(false);//from  w  w w. ja va  2s.  c  o  m
        conn.setHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(requestQuery);
        conn.setReadTimeout(10000);
        conn.connect();
        System.out.println(conn.getRequestMethod());
        // Get the response
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = null;
        try {
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.defaultCharset()));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
        } catch (FileNotFoundException ignored) {
        } finally {
            if (rd != null) {
                rd.close();
            }
            wr.flush();
            wr.close();
            conn.disconnect();
        }
        return new HttpsResponse(sb.toString(), conn.getResponseCode());
    }
    return null;
}

From source file:org.wso2.carbon.automation.test.utils.http.client.HttpsURLConnectionClient.java

public static HttpsResponse putWithBasicAuth(String uri, String requestQuery, String contentType,
        String userName, String password) throws IOException {
    if (uri.startsWith("https://")) {
        URL url = new URL(uri);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        String encode = new String(
                new org.apache.commons.codec.binary.Base64().encode((userName + ":" + password).getBytes()))
                        .replaceAll("\n", "");
        ;/*ww  w . ja  v a 2s . com*/
        conn.setRequestProperty("Authorization", "Basic " + encode);
        conn.setDoOutput(true); // Triggers POST.
        conn.setRequestProperty("Content-Type", contentType);
        conn.setRequestProperty("charset", "utf-8");
        conn.setRequestProperty("Content-Length", "" + Integer.toString(requestQuery.getBytes().length));
        conn.setUseCaches(false);
        conn.setHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(requestQuery);
        conn.setReadTimeout(10000);
        conn.connect();
        // Get the response
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = null;
        try {
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.defaultCharset()));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
        } catch (FileNotFoundException ignored) {
        } finally {
            if (rd != null) {
                rd.close();
            }
            wr.flush();
            wr.close();
            conn.disconnect();
        }
        return new HttpsResponse(sb.toString(), conn.getResponseCode());
    }
    return null;
}

From source file:com.mhise.util.MHISEUtil.java

public static KeyStore getServerKeyStore(String url) {
    KeyStore ks = null;/* www .j ava  2s .  com*/
    try {
        MHISETrustManager.allowAllSSL();
        HttpsURLConnection connection = (HttpsURLConnection) (new URL(url)).openConnection();

        connection.connect();

        Certificate[] certs = connection.getServerCertificates();
        ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(null, null);
        ks.setCertificateEntry("servercert", certs[0]);
        Log.i("MHISEUtil-->getServerKeyStore", certs[0].getPublicKey().toString());
    } catch (Exception e) {

        Logger.debug("MHISEUtil-->getServerKeyStore", "Exception" + e);
        e.printStackTrace();
    }
    return ks;
}

From source file:org.wso2.carbon.automation.test.utils.http.client.HttpsURLConnectionClient.java

public static HttpsResponse postWithBasicAuth(String uri, String requestQuery, String userName, String password)
        throws IOException {
    if (uri.startsWith("https://")) {
        URL url = new URL(uri);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        String encode = new String(
                new org.apache.commons.codec.binary.Base64().encode((userName + ":" + password).getBytes()))
                        .replaceAll("\n", "");
        ;/*from w w  w  .j av a2  s .com*/
        conn.setRequestProperty("Authorization", "Basic " + encode);
        conn.setDoOutput(true); // Triggers POST.
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("charset", "utf-8");
        conn.setRequestProperty("Content-Length", "" + Integer.toString(requestQuery.getBytes().length));
        conn.setUseCaches(false);
        conn.setHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(requestQuery);
        conn.setReadTimeout(10000);
        conn.connect();
        System.out.println(conn.getRequestMethod());
        // Get the response
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = null;
        try {
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.defaultCharset()));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
            return new HttpsResponse(sb.toString(), conn.getResponseCode());
        } catch (FileNotFoundException ignored) {
        } finally {
            if (rd != null) {
                rd.close();
            }
            wr.flush();
            wr.close();
            conn.disconnect();
        }
    }
    return null;
}

From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImplIT.java

@Test
@Ignore/*from  w  ww .  j a v  a2s.c  o  m*/
public void testCredentialManager() throws CMException, URISyntaxException, IOException {

    // There are 3 service username and password entries in the Keystore
    List<URI> serviceList = credentialManager.getServiceURIsForAllUsernameAndPasswordPairs();
    assertTrue(serviceList.size() == 3);
    System.out.println();
    assertTrue(serviceList.contains(serviceURI2));

    credentialManager.deleteUsernameAndPasswordForService(serviceURI3);
    assertFalse(credentialManager.hasUsernamePasswordForService(serviceURI3));

    // There are 2 private/public key pair entries in the Keystore
    credentialManager.hasKeyPair(privateKey, privateKeyCertChain);

    // There are Google's and heater.cs.man.ac's trusted certificates in the Truststore
    credentialManager.hasTrustedCertificate(trustedCertficateGoogle);
    // Open a HTTPS connection to Google
    URL url = new URL("https://code.google.com/p/taverna/");
    HttpsURLConnection conn;
    conn = (HttpsURLConnection) url.openConnection();
    // This should work
    conn.connect();
    assertEquals("HTTP/1.1 200 OK", conn.getHeaderField(0));
    conn.disconnect();

    credentialManager.hasTrustedCertificate(trustedCertficateHeater);
    // Open a HTTPS connection to heater
    url = new URL("https://heater.cs.man.ac.uk:7443/");
    conn = (HttpsURLConnection) url.openConnection();
    // This should work
    conn.connect();
    assertEquals("HTTP/1.1 200 OK", conn.getHeaderField(0));
    conn.disconnect();

}

From source file:Activities.java

private String addData(String endpoint) {
    String data = null;/*from   ww  w.  j  ava2 s  . c om*/
    try {
        // Construct request payload
        JSONObject attrObj = new JSONObject();
        attrObj.put("name", "URL");
        attrObj.put("value", "http://www.nvidia.com/game-giveaway");

        JSONArray attrArray = new JSONArray();
        attrArray.add(attrObj);

        TimeZone tz = TimeZone.getTimeZone("UTC");
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
        df.setTimeZone(tz);
        String dateAsISO = df.format(new Date());

        // Required attributes
        JSONObject obj = new JSONObject();
        obj.put("leadId", "1001");
        obj.put("activityDate", dateAsISO);
        obj.put("activityTypeId", "1001");
        obj.put("primaryAttributeValue", "Game Giveaway");
        obj.put("attributes", attrArray);
        System.out.println(obj);

        // Make request
        URL url = new URL(endpoint);
        HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
        urlConn.setRequestMethod("POST");
        urlConn.setAllowUserInteraction(false);
        urlConn.setDoOutput(true);
        urlConn.setRequestProperty("Content-type", "application/json");
        urlConn.setRequestProperty("accept", "application/json");
        urlConn.connect();
        OutputStream os = urlConn.getOutputStream();
        os.write(obj.toJSONString().getBytes());
        os.close();

        // Inspect response
        int responseCode = urlConn.getResponseCode();
        if (responseCode == 200) {
            System.out.println("Status: 200");
            InputStream inStream = urlConn.getInputStream();
            data = convertStreamToString(inStream);
            System.out.println(data);
        } else {
            System.out.println(responseCode);
            data = "Status:" + responseCode;
        }
    } catch (MalformedURLException e) {
        System.out.println("URL not valid.");
    } catch (IOException e) {
        System.out.println("IOException: " + e.getMessage());
        e.printStackTrace();
    }

    return data;
}

From source file:com.logger.TrackServlet.java

private String getJsonData(String ip) {
    String result = "";
    try {/*w w w.  jav  a  2s. c om*/
        URL url = new URL("https://stat.ripe.net/data/whois/data.json?resource=" + ip);
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        connection.connect();
        int status = connection.getResponseCode();
        if (status == 200) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line = "";
            while ((line = reader.readLine()) != null) {
                result += line;
            }
        }
    } catch (MalformedURLException ex) {
        Logger.getLogger(TrackServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(TrackServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
    return result;
}

From source file:net.sf.taverna.t2.security.credentialmanager.impl.HTTPSConnectionAndTrustConfirmationIT.java

@Test
public void testTrustConfirmationProvidersTrustAlways() throws IOException, CMException {
    // Initially trust provider list is empty, we only verify by what is in 
    // Credential Manager's Truststore (and it does not contains the certificate for https://heater.cs.man.ac.uk:7443/)

    // Do not forget to initialise Taverna's/Credential Manager's SSLSocketFactory
    credentialManager.initializeSSL();//from ww w  .j  av a2 s.  c  o  m

    URL url = new URL("https://heater.cs.man.ac.uk:7443/");
    HttpsURLConnection conn;
    conn = (HttpsURLConnection) url.openConnection();
    try {
        // This should fail
        conn.connect();
        fail("Connection to https://heater.cs.man.ac.uk:7443/ should be untrusted at this point.");
    } catch (SSLHandshakeException sslex) {
        // expected to fail so all is good
        System.out.println(sslex.getStackTrace());
    } finally {
        conn.disconnect();
    }

    // Add the trust confirmation provider that trusts everyone
    List<TrustConfirmationProvider> trustProviders = new ArrayList<TrustConfirmationProvider>();
    trustProviders.add(new TrustAlwaysTrustConfirmationProvider());
    credentialManager.setTrustConfirmationProviders(trustProviders);

    HttpsURLConnection conn2 = (HttpsURLConnection) url.openConnection();
    // This should work now
    conn2.connect();
    System.out.println("Status header: " + conn2.getHeaderField(0));

    assertEquals("HTTP/1.1 200 OK", conn2.getHeaderField(0));
    conn2.disconnect();
}

From source file:net.sf.taverna.t2.security.credentialmanager.impl.HTTPSConnectionAndTrustConfirmationIT.java

@Test
public void testTrustConfirmationProvidersTrustNever() throws IOException, CMException {
    // Initially trust provider list is empty, we only verify by what is in 
    // Credential Manager's Truststore (and it does not contains the certificate for https://heater.cs.man.ac.uk:7443/)

    // Do not forget to initialise Taverna's/Credential Manager's SSLSocketFactory
    credentialManager.initializeSSL();/*  w  w w.j a v a2 s  .  co m*/

    URL url = new URL("https://heater.cs.man.ac.uk:7443/");
    HttpsURLConnection conn;
    conn = (HttpsURLConnection) url.openConnection();
    try {
        // This should fail
        conn.connect();
        fail("Connection to https://heater.cs.man.ac.uk:7443/ should be untrusted at this point.");
    } catch (SSLHandshakeException sslex) {
        // expected to fail so all is good
    } finally {
        conn.disconnect();
    }

    // Add the trust confirmation provider that trusts no one
    List<TrustConfirmationProvider> trustProviders = new ArrayList<TrustConfirmationProvider>();
    credentialManager.setTrustConfirmationProviders(trustProviders);
    trustProviders = new ArrayList<TrustConfirmationProvider>();
    trustProviders.add(new TrustNeverTrustConfimationProvider());
    credentialManager.setTrustConfirmationProviders(trustProviders);

    HttpsURLConnection conn2 = (HttpsURLConnection) url.openConnection();
    try {
        // This should still fail as our trust providers are not trusting anyone
        // and we have not added heater's certificate to Credential Manager's Truststore
        conn2.connect();
        fail("Connection to https://heater.cs.man.ac.uk:7443/ should be untrusted at this point.");
    } catch (SSLHandshakeException sslex) {
        // expected to fail so all is good
    } finally {
        conn2.disconnect();
    }
}