Example usage for javax.net.ssl HttpsURLConnection getInputStream

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

Introduction

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

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Returns an input stream that reads from this open connection.

Usage

From source file:org.openadaptor.util.PropertiesPoster.java

/**
 * Utility method which will attempt to POST the supplied properties information to the supplied URL.
 * //  w  w  w.j a v  a2  s .c  om
 * This method currently contains an all trusting trust manager for use with https. This will be replaced with a more
 * secure trust manager which will use a cert store.
 * 
 * @param registrationURL
 * @param properties
 * @throws Exception
 */
protected static void syncPostHttp(String registrationURL, Properties properties) throws Exception {

    URL url = new URL(registrationURL);
    String postData = generatePOSTData(properties);
    log.debug("Protocol: " + url.getProtocol());
    if (url.getProtocol().equals("https")) {

        // https connection

        // TODO: Replace this all trusting manager with one that uses a cert store
        // Create a trust manager that does not validate certificate chains
        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) {
            }
        } };

        // Install the all-trusting trust manager
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());

        HttpsURLConnection secureConnection = null;
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        secureConnection = (HttpsURLConnection) url.openConnection();
        secureConnection.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(secureConnection.getOutputStream());
        writer.write(postData);
        writer.flush();
        int responseCode = secureConnection.getResponseCode();
        if (HttpsURLConnection.HTTP_OK != responseCode) {
            log.error("\nFailed to register. Response Code " + responseCode + "\nResponse message:"
                    + secureConnection.getResponseMessage() + "\nRegistration URL: " + registrationURL
                    + "\nData: " + generateString(properties));
        }
        BufferedReader br = new BufferedReader(new InputStreamReader(secureConnection.getInputStream()));
        String line;
        while ((line = br.readLine()) != null) {
            log.debug("Returned data: " + line);
        }
        writer.close();
        br.close();
    } else {

        // Normal http connection
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
        writer.write(postData);
        writer.flush();
        int responseCode = connection.getResponseCode();
        if (HttpURLConnection.HTTP_OK != responseCode) {
            log.error("\nFailed to register. Response Code " + responseCode + "\nResponse message:"
                    + connection.getResponseMessage() + "\nRegistration URL: " + registrationURL + "\nData: "
                    + generateString(properties));
        }
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        while ((line = br.readLine()) != null) {
            log.debug("Returned data: " + line);
        }
        writer.close();
        br.close();
    }
}

From source file:xyz.karpador.godfishbot.commands.TrumpCommand.java

@Override
public CommandResult getReply(String params, Message message, String myName) {
    try {/*from w w w  .j  a  va 2  s .  c o m*/
        URL url = new URL("https://api.whatdoestrumpthink.com/api/v1/quotes/random");
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
        if (con.getResponseCode() == HTTP_OK) {
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String result = br.readLine();
            JSONObject resultJson = new JSONObject(result);
            return new CommandResult(resultJson.getString("message"));
        }
    } catch (IOException | JSONException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.hybris.mobile.data.WebServiceDataProvider.java

/**
 * Synchronous call for logging in/*from www . jav  a2s. c  o m*/
 * 
 * @param httpBody
 * @return The data from the server as a string, in almost all cases JSON
 * @throws MalformedURLException
 * @throws IOException
 * @throws JSONException
 */
public static String getLoginResponse(Bundle httpBody) throws MalformedURLException, IOException {
    String response = "";
    URL url = new URL(WebServiceAuthProvider.tokenURL());
    trustAllHosts();
    HttpsURLConnection connection = createSecureConnection(url);
    connection.setHostnameVerifier(DO_NOT_VERIFY);
    String authString = "mobile_android:secret";
    String authValue = "Basic " + Base64.encodeToString(authString.getBytes(), Base64.NO_WRAP);

    connection.setRequestMethod("POST");
    connection.setRequestProperty("Authorization", authValue);
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.connect();

    OutputStream os = new BufferedOutputStream(connection.getOutputStream());
    os.write(encodePostBody(httpBody).getBytes());
    os.flush();
    try {
        LoggingUtils.d(LOG_TAG, connection.toString());
        response = readFromStream(connection.getInputStream());
    } catch (MalformedURLException e) {
        LoggingUtils.e(LOG_TAG,
                "Error reading stream \"" + connection.getInputStream() + "\". " + e.getLocalizedMessage(),
                null);
    } catch (IOException e) {
        response = readFromStream(connection.getErrorStream());
    } finally {
        connection.disconnect();
    }

    return response;
}

From source file:org.jboss.aerogear.adm.TokenService.java

/**
 * To obtain an access token, make an HTTPS request to Amazon
 * and include your client_id and client_secret values.
 * //from   w ww. ja  v a  2s  .co m
 * @param clientId unique ID supplied by ADM Services
 * @param clientSecret secret value supplied by ADM services
 * @return a String containing your auth token
 * @throws Exception if retrieving the Auth token fails
 */
public String getAuthToken(String clientId, String clientSecret) throws Exception {
    // Encode the body of your request, including your clientID and clientSecret values.
    String body = "grant_type=" + URLEncoder.encode(CLIENT_CREDENTIALS, UTF_8) + "&" + "scope="
            + URLEncoder.encode(MESSAGING_PUSH, UTF_8) + "&" + "client_id=" + URLEncoder.encode(clientId, UTF_8)
            + "&" + "client_secret=" + URLEncoder.encode(clientSecret, UTF_8);

    // Generate the HTTPS connection. You cannot make a connection over HTTP.
    final HttpsURLConnection con = post(body);

    // Convert the response into a String object.
    final String responseContent = parseResponse(con.getInputStream());

    // Create a new JSONObject to hold the access token and extract
    // the token from the response.
    final JSONObject parsedObject = new org.json.JSONObject(responseContent);
    final String accessToken = parsedObject.getString("access_token");
    return accessToken;
}

From source file:it.serverSystem.HttpsTest.java

private void connectTrusted() throws IOException {
    URL url = new URL("https://localhost:" + httpsPort);
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    try {/*from ww  w.java 2s.  c o m*/
        connection.getInputStream();
        fail();
    } catch (SSLHandshakeException e) {
        // ok, the certificate is not trusted
    }
}

From source file:com.raphfrk.craftproxyclient.net.auth.AuthManager.java

public static JSONObject sendRequest(JSONObject request, String endpoint) {
    URL url;//from   w ww  .jav  a 2 s  . co  m
    try {
        url = new URL(authServer + "/" + endpoint);
    } catch (MalformedURLException e) {
        return null;
    }
    try {
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
        con.setDoOutput(true);
        con.setInstanceFollowRedirects(false);
        con.setReadTimeout(5000);
        con.setConnectTimeout(5000);
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json");
        con.connect();

        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(con.getOutputStream(), StandardCharsets.UTF_8));
        try {
            request.writeJSONString(writer);
            writer.flush();
            writer.close();

            if (con.getResponseCode() != 200) {
                return null;
            }

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
            try {
                JSONParser parser = new JSONParser();

                try {
                    return (JSONObject) parser.parse(reader);
                } catch (ParseException e) {
                    return null;
                }
            } finally {
                reader.close();
            }
        } finally {
            writer.close();
            con.disconnect();
        }
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

}

From source file:fr.qinder.api.APIGetter.java

protected InputStream getInputStream(HttpsURLConnection request) throws IOException {
    InputStream res;/*from   w  w w .j a va  2  s.  c o  m*/

    if (request.getResponseCode() == HttpStatus.SC_OK) {
        res = request.getInputStream();
    } else {
        res = request.getErrorStream();
    }
    return res;
}

From source file:org.apache.hadoop.io.crypto.bee.RestClient.java

private InputStream httpsIgnoreCertificate(final URL url) throws IOException {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }//from ww w  .j a v  a 2s. c  o  m

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }
    } };

    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        ;
    }

    HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
    return urlConnection.getInputStream();

}

From source file:com.longtime.ajy.support.weixin.HttpsKit.java

/**
 * ??Get// w w  w  . j ava 2s  . co m
 * 
 * @param url
 * @return
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws IOException
 * @throws KeyManagementException
 */
public static String get(String url) {//throws NoSuchAlgorithmException, NoSuchProviderException, IOException, KeyManagementException {
    InputStream in = null;
    HttpsURLConnection http = null;

    try {
        StringBuffer bufferRes = null;
        TrustManager[] tm = { new MyX509TrustManager() };
        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
        sslContext.init(null, tm, new java.security.SecureRandom());
        // SSLContextSSLSocketFactory  
        SSLSocketFactory ssf = sslContext.getSocketFactory();

        URL urlGet = new URL(url);
        http = (HttpsURLConnection) urlGet.openConnection();
        // 
        http.setConnectTimeout(TIME_OUT_CONNECT);
        // ? --??
        http.setReadTimeout(TIME_OUT_READ);
        http.setRequestMethod("GET");
        http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        http.setSSLSocketFactory(ssf);
        http.setDoOutput(true);
        http.setDoInput(true);
        http.connect();

        in = http.getInputStream();
        BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
        String valueString = null;
        bufferRes = new StringBuffer();
        while ((valueString = read.readLine()) != null) {
            bufferRes.append(valueString);
        }
        return bufferRes.toString();
    } catch (Exception e) {
        logger.error(String.format("HTTP GET url=[%s] due to fail.", url), e);
    } finally {
        if (null != in) {
            try {
                in.close();
            } catch (IOException e) {
                logger.error(String.format("HTTP GET url=[%s] close inputstream due to fail.", url), e);
            }
        }
        if (http != null) {
            // 
            http.disconnect();
        }
    }

    return StringUtils.EMPTY;

}

From source file:heanetmedia.models.MediaList.java

/**
* Simple curl function adapted for https to make a GET request to media.heanet.ie and retrieve the output
* @params String purl - full url for the request
* @return String Output from the request
*///  w ww . j  a v a  2s  . co  m
private String curl(String purl) {
    String curl = "", line = null;

    try {
        URL url = new URL(purl);
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();

        BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));

        while ((line = br.readLine()) != null) {
            curl += line;
        }

        br.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return curl;
}