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.encuestame.core.util.SocialUtils.java

/**
 * Get Google Short Url./* w ww. j a va  2  s.c  o m*/
 * @return
 */
public static String getGoGl(final String urlPath, String key) {
    log.debug("getGoGl url " + urlPath);
    log.debug("getGoGl key " + key);
    String shortUrl = null;
    URL simpleURL = null;
    HttpsURLConnection url = null;
    BufferedInputStream bStream = null;
    StringBuffer resultString = new StringBuffer("");
    String inputString = "{\"longUrl\":\"" + urlPath + "\"}";
    log.debug("getGoGl inputString " + inputString);
    try {
        simpleURL = new URL("https://www.googleapis.com/urlshortener/v1/url?key=" + key);
        url = (HttpsURLConnection) simpleURL.openConnection();
        url.setDoOutput(true);
        url.setRequestProperty("content-type", "application/json");
        PrintWriter pw = new PrintWriter(url.getOutputStream());
        pw.print(inputString);
        pw.close();
    } catch (Exception ex) {
        log.error(ex);
        shortUrl = urlPath;
    }
    try {
        bStream = new BufferedInputStream(url.getInputStream());
        int i;
        while ((i = bStream.read()) >= 0) {
            resultString.append((char) i);
        }
        //  final Object jsonObject = JSONValue.parse(resultString.toString());
        //   final JSONObject o = (JSONObject) jsonObject;
        //   shortUrl = (String) o.get("id");
    } catch (Exception ex) {
        SocialUtils.log.error(ex);
        shortUrl = urlPath;
    }
    return shortUrl;
}

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

/**
 * Synchronous call for logging out// ww w .  j ava 2  s  .c  om
 * 
 * @return The data from the server as a string, in almost all cases JSON
 * @throws MalformedURLException
 * @throws IOException
 * @throws JSONException
 */
public static String getLogoutResponse(Context context)
        throws MalformedURLException, IOException, JSONException {
    // Refresh if necessary
    if (WebServiceAuthProvider.tokenExpiredHint(context)) {
        WebServiceAuthProvider.refreshAccessToken(context);
    }

    boolean refreshLimitReached = false;
    int refreshed = 0;

    String response = "";
    while (!refreshLimitReached) {
        // If we have refreshed max number of times, we will not do so again
        if (refreshed == 1) {
            refreshLimitReached = true;
        }

        URL url = new URL(urlForLogout(context));
        HttpsURLConnection connection = createSecureConnection(url);
        trustAllHosts();
        connection.setHostnameVerifier(DO_NOT_VERIFY);
        String authValue = "Bearer " + SDKSettings.getSharedPreferenceString(context, "access_token");

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

        try {
            LoggingUtils.d(LOG_TAG, "LogoutResponse" + 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();
        }

        // Allow for calls to return nothing
        if (response.length() == 0) {
            return "";
        }

        // Check for JSON parsing errors (will throw JSONException is can't be parsed)
        JSONObject object = new JSONObject(response);

        // If no error, return response
        if (!object.has("error")) {
            return response;
        }
        // If there is a refresh token error, refresh the token
        else if (object.getString("error").equals("invalid_token")) {
            if (refreshLimitReached) {
                // Give up
                return response;
            } else {
                // Refresh the token
                WebServiceAuthProvider.refreshAccessToken(context);
                refreshed++;
            }
        }
    } // while(!refreshLimitReached)

    return response;
}

From source file:org.wise.portal.presentation.web.filters.WISEAuthenticationProcessingFilter.java

/**
 * Check if the response is valid//from   w  ww  .  j av a 2  s.  c  o  m
 * @param reCaptchaPrivateKey the ReCaptcha private key
 * @param reCaptchaPublicKey the ReCaptcha public key
 * @param gRecaptchaResponse the response
 * @return whether the user answered the ReCaptcha successfully
 */
public static boolean checkReCaptchaResponse(String reCaptchaPrivateKey, String reCaptchaPublicKey,
        String gRecaptchaResponse) {

    boolean isValid = false;

    //check if the public key is valid in case the admin entered it wrong
    boolean reCaptchaKeyValid = isReCaptchaKeyValid(reCaptchaPublicKey, reCaptchaPrivateKey);

    if (reCaptchaKeyValid && reCaptchaPrivateKey != null && reCaptchaPublicKey != null
            && gRecaptchaResponse != null && !gRecaptchaResponse.equals("")) {

        try {

            // the url to verify the response
            URL verifyURL = new URL("https://www.google.com/recaptcha/api/siteverify");
            HttpsURLConnection connection = (HttpsURLConnection) verifyURL.openConnection();
            connection.setRequestMethod("POST");

            // set the params
            String postParams = "secret=" + reCaptchaPrivateKey + "&response=" + gRecaptchaResponse;

            // make the request to verify if the user answered the ReCaptcha successfully
            connection.setDoOutput(true);
            DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.writeBytes(postParams);
            outputStream.flush();
            outputStream.close();

            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(connection.getInputStream()));
            String inputLine = null;
            StringBuffer responseString = new StringBuffer();

            // read the response from the verify request
            while ((inputLine = bufferedReader.readLine()) != null) {
                responseString.append(inputLine);
            }

            bufferedReader.close();

            try {
                // create a JSON object from the response
                JSONObject responseObject = new JSONObject(responseString.toString());

                // get the value of the success field
                isValid = responseObject.getBoolean("success");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return isValid;
}

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

public static HttpsResponse getWithBasicAuth(String Uri, String requestParameters, String userName,
        String password) throws IOException {
    if (Uri.startsWith("https://")) {
        String urlStr = Uri;//  w w  w  .  j a  v a 2 s  . com
        if (requestParameters != null && requestParameters.length() > 0) {
            urlStr += "?" + requestParameters;
        }
        URL url = new URL(urlStr);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        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);
        conn.setHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        conn.setReadTimeout(30000);
        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();
            }
            conn.disconnect();
        }
        return new HttpsResponse(sb.toString(), conn.getResponseCode());
    }
    return null;
}

From source file:org.liberty.android.fantastischmemo.downloader.google.GoogleAccountActivity.java

@Override
protected boolean verifyAccessToken(final String[] accessTokens) throws IOException {
    String token = accessTokens[0];
    try {//from  ww w .ja va  2 s .c  om
        URL url1 = new URL("https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=" + token);
        HttpsURLConnection conn = (HttpsURLConnection) url1.openConnection();

        String s = new String(IOUtils.toByteArray(conn.getInputStream()));
        JSONObject jsonObject = new JSONObject(s);
        if (jsonObject.has("error")) {
            String error = jsonObject.getString("error");
            Log.e(TAG, "Token validation error: " + error);
            return false;
        }

        String audience = jsonObject.getString("audience");
        return AMEnv.GOOGLE_CLIENT_ID.equals(audience);
    } catch (Exception e) {
        Log.i(TAG, "The saved access token is invalid", e);
    }
    return false;
}

From source file:com.ibm.mobilefirst.mobileedge.utils.RequestUtils.java

public static void executeTrainRequest(String name, String uuid, List<AccelerometerData> accelerometerData,
        List<GyroscopeData> gyroscopeData, RequestResult requestResult) throws IOException {

    URL url = new URL("https://medge.mybluemix.net/alg/train");

    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setReadTimeout(5000);/*from   ww  w  .  j  a v a2 s .  c  o m*/
    conn.setConnectTimeout(10000);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json");

    conn.setDoInput(true);
    conn.setDoOutput(true);

    JSONObject jsonToSend = createTrainBodyJSON(name, uuid, accelerometerData, gyroscopeData);

    OutputStream outputStream = conn.getOutputStream();
    DataOutputStream wr = new DataOutputStream(outputStream);
    wr.writeBytes(jsonToSend.toString());
    wr.flush();
    wr.close();

    outputStream.close();

    String response = "";

    int responseCode = conn.getResponseCode();

    //Log.e("BBB2","" + responseCode);

    if (responseCode == HttpsURLConnection.HTTP_OK) {
        String line;
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        while ((line = br.readLine()) != null) {
            response += line;
        }
    } else {
        response = "{}";
    }

    handleResponse(response, requestResult);
}

From source file:core.Web.java

public static JSONObject httpsRequest(URL url, Map<String, String> properties, JSONObject message) {
    //        System.out.println(url);
    try {/*from   w  w w .j  a v a2 s.c o  m*/
        // Create connection
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        //connection.addRequestProperty("Authorization", API_KEY);
        // Set properties if needed
        if (properties != null && !properties.isEmpty()) {
            properties.forEach(connection::setRequestProperty);
        }
        // Post message
        if (message != null) {
            // Maybe somewhere
            connection.setDoOutput(true);
            try (BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(connection.getOutputStream()))) {
                writer.write(message.toString());
            }
        }
        // Establish connection
        connection.connect();
        int responseCode = connection.getResponseCode();

        if (responseCode != 200) {
            throw new RuntimeException("Response code was not 200. Detected response was " + responseCode);
        }

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
            String line;
            String content = "";
            while ((line = reader.readLine()) != null) {
                content += line;
            }
            return new JSONObject(content);
        }

    } catch (IOException ex) {
        Logger.getLogger(Web.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:ke.co.tawi.babblesms.server.servlet.accountmngmt.Login.java

public static boolean validateCaptcha(String gRecaptchaResponse) throws IOException {
    if (gRecaptchaResponse == null || "".equals(gRecaptchaResponse)) {
        return false;
    }/*  w ww.j a v a 2  s  .  com*/

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

        // add reuqest header
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        String postParams = "secret=" + secret + "&response=" + gRecaptchaResponse;

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(postParams);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + postParams);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        // print result
        System.out.println(response.toString());

        //parse JSON response and return 'success' value
        JsonReader jsonReader = Json.createReader(new StringReader(response.toString()));
        JsonObject jsonObject = jsonReader.readObject();
        jsonReader.close();

        return jsonObject.getBoolean("success");
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

From source file:org.apache.sentry.provider.db.service.thrift.TestSentryWebServerWithSSL.java

@Test
public void testPing() throws Exception {
    final URL url = new URL("https://" + SentryServiceIntegrationBase.SERVER_HOST + ":"
            + SentryServiceIntegrationBase.webServerPort + "/ping");
    Properties systemProps = System.getProperties();
    systemProps.put("javax.net.ssl.trustStore", Resources.getResource("cacerts.jks").getPath());
    System.setProperties(systemProps);
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    Assert.assertEquals(HttpsURLConnection.HTTP_OK, conn.getResponseCode());
    String response = IOUtils.toString(conn.getInputStream());
    Assert.assertEquals("pong\n", response);
}

From source file:org.apache.sentry.api.service.thrift.TestSentryWebServerWithSSL.java

@Test
public void testPing() throws Exception {
    final URL url = new URL("https://" + SERVER_HOST + ":" + webServerPort + "/ping");
    Properties systemProps = System.getProperties();
    systemProps.put("javax.net.ssl.trustStore", Resources.getResource("cacerts.jks").getPath());
    System.setProperties(systemProps);
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    Assert.assertEquals(HttpsURLConnection.HTTP_OK, conn.getResponseCode());
    String response = IOUtils.toString(conn.getInputStream());
    Assert.assertEquals("pong\n", response);
}