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.schabi.newpipe.Downloader.java

/**Common functionality between download(String url) and download(String url, String language)*/
private static String dl(HttpsURLConnection con) throws IOException {
    StringBuilder response = new StringBuilder();

    try {/*  w  w  w. j  a  va 2s  .  co  m*/
        con.setRequestMethod("GET");
        con.setRequestProperty("User-Agent", USER_AGENT);

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

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

    } catch (UnknownHostException uhe) {//thrown when there's no internet connection
        uhe.printStackTrace();
        //Toast.makeText(getActivity(), uhe.getMessage(), Toast.LENGTH_LONG).show();
    }

    return response.toString();
}

From source file:org.liberty.android.fantastischmemo.downloader.quizlet.lib.java

public static boolean verifyAccessToken(final String[] accessTokens) throws Exception {
    final String TAG = "verfyAccessToken";
    String token = accessTokens[0];
    String userId = accessTokens[1];
    try {//from  ww w .  j  a  v a 2 s .  c  o  m
        URL url1 = new URL(QUIZLET_API_ENDPOINT + "/users/" + userId);
        HttpsURLConnection conn = (HttpsURLConnection) url1.openConnection();
        conn.addRequestProperty("Authorization", "Bearer " + String.format(token));

        JsonReader s = new JsonReader(new InputStreamReader((conn.getInputStream()), "UTF-8"));
        s.beginObject();
        while (s.hasNext()) {
            String name = s.nextName();
            if ("error".equals(name)) {
                String error = s.nextString();
                Log.e(TAG, "Token validation error: " + error);
                return false;
            } else {
                s.skipValue();
            }
        }
        s.endObject();
        s.close();

    } catch (Exception e) {
        Log.i(TAG, "The saved access token is invalid", e);
        return false;
    }
    return true;
}

From source file:org.openengsb.connector.facebook.internal.FacebookNotifier.java

private static String sendData(String httpsURL, String params) throws Exception {
    LOGGER.info("sending facebook-message");
    URL myurl = new URL(httpsURL);
    HttpsURLConnection con = (HttpsURLConnection) myurl.openConnection();
    if (params != null) {
        con.setDoOutput(true);/* w w w .  j  a va  2  s .c o m*/
        con.setRequestMethod("POST");
        OutputStreamWriter ow = new OutputStreamWriter(con.getOutputStream());
        ow.write(params);
        ow.flush();
        ow.close();
    }
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));

    StringBuffer output = new StringBuffer();
    String inputLine;

    while ((inputLine = in.readLine()) != null) {
        output.append(inputLine);
        LOGGER.debug(inputLine);
    }
    in.close();
    LOGGER.info("facebook message has been sent");
    return output.toString();
}

From source file:com.ct855.util.HttpsClientUtil.java

public static String getUrl(String url)
        throws IOException, NoSuchAlgorithmException, KeyManagementException, NoSuchProviderException {
    //SSLContext??
    TrustManager[] trustAllCerts = new TrustManager[] { new MyX509TrustManager() };
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
    sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

    //SSLContextSSLSocketFactory
    SSLSocketFactory ssf = sslContext.getSocketFactory();

    URL aURL = new java.net.URL(url);
    HttpsURLConnection aConnection = (HttpsURLConnection) aURL.openConnection();
    aConnection.setRequestProperty("Ocp-Apim-Subscription-Key", "d8400b4cdf104015bb23d7fe847352c8");
    aConnection.setSSLSocketFactory(ssf);
    aConnection.setDoOutput(true);//from   w w  w.  j ava 2 s  . c  om
    aConnection.setDoInput(true);
    aConnection.setRequestMethod("GET");

    InputStream resultStream = aConnection.getInputStream();
    BufferedReader aReader = new java.io.BufferedReader(new java.io.InputStreamReader(resultStream));
    StringBuffer aResponse = new StringBuffer();
    String aLine = aReader.readLine();
    while (aLine != null) {
        aResponse.append(aLine + "\n");
        aLine = aReader.readLine();
    }
    resultStream.close();
    return aResponse.toString();
}

From source file:org.liberty.android.fantastischmemo.downloader.quizlet.lib.java

/**
 * Make API call to Quizlet server with oauth
 *
 * @param url/*from ww w  . ja  v  a 2 s  .  c  o m*/
 *            API call endpoint
 * @param authToken
 *            oauth auth token
 * @return Response of API call
 * @throws IOException
 *             If http response code is not 2xx
 */
public static InputStream makeApiCall(URL url, String authToken) throws IOException {
    HttpsURLConnection conn = null;
    try {
        conn = (HttpsURLConnection) url.openConnection();
        if (authToken != null) {
            conn.addRequestProperty("Authorization", "Bearer " + authToken);
        }

        InputStream response = conn.getInputStream();
        if (conn.getResponseCode() / 100 >= 3) {
            response = conn.getErrorStream();
        }
        return response;
    } finally {
        //conn.disconnect();
    }
}

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

public static ByteArrayOutputStream doGetImg(String url, String cookieStr) {
    InputStream in = null;//  w  w w.j a va 2s. co  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:com.coinprism.model.APIClient.java

private static String getHttpResponse(HttpsURLConnection connection) throws IOException, APIException {
    int responseCode = connection.getResponseCode();

    if (responseCode < 400) {
        InputStream inputStream = new BufferedInputStream(connection.getInputStream());

        return readStream(inputStream);
    } else {/*w ww  .j a  va2 s .  co m*/
        InputStream inputStream = new BufferedInputStream(connection.getErrorStream());
        String response = readStream(inputStream);
        try {
            JSONObject error = new JSONObject(response);
            String errorCode = error.getString("ErrorCode");
            String subCode = error.optString("SubCode");

            throw new APIException(errorCode, subCode);
        } catch (JSONException exception) {
            throw new IOException(exception.getMessage());
        }
    }
}

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

static private StringBuffer ProcessRequest(HttpsURLConnection http) throws IOException {
    http.connect();/*from  w  ww . j  ava2s.co  m*/

    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;
    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:com.versobit.weatherdoge.WeatherUtil.java

private static WeatherResult getWeatherFromYahoo(double latitude, double longitude, String location) {
    try {/* w  w w .j a  va  2  s  . co  m*/
        String yqlText;
        if (latitude == Double.MIN_VALUE && longitude == Double.MIN_VALUE) {
            if (location == null) {
                return new WeatherResult(null, WeatherResult.ERROR_THROWABLE, "No valid location parameters.",
                        new IllegalArgumentException());
            }
            yqlText = location.replaceAll("[^\\p{L}\\p{Nd} ,-]+", "");
        } else {
            yqlText = String.valueOf(latitude) + ", " + String.valueOf(longitude);
        }
        URL url = new URL("https://query.yahooapis.com/v1/public/yql?q=" + URLEncoder.encode(
                "select location.city, units, item.condition, astronomy from weather.forecast where woeid in (select woeid from geo.placefinder where text = \""
                        + yqlText + "\" and gflags = \"R\" limit 1) limit 1",
                "UTF-8") + "&format=json");
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        try {
            JSONObject response = new JSONObject(IOUtils.toString(connection.getInputStream()));
            if (connection.getResponseCode() != HttpsURLConnection.HTTP_OK) {
                JSONObject error = response.getJSONObject("error");
                return new WeatherResult(null, WeatherResult.ERROR_API, error.getString("description"), null);
            }
            JSONObject query = response.getJSONObject("query");
            if (query.getInt("count") == 0) {
                return new WeatherResult(null, WeatherResult.ERROR_API, "No results found for that location.",
                        null);
            }

            JSONObject channel = query.getJSONObject("results").getJSONObject("channel");
            JSONObject units = channel.getJSONObject("units");
            JSONObject condition = channel.getJSONObject("item").getJSONObject("condition");
            JSONObject astronomy = channel.getJSONObject("astronomy");

            double temp = condition.getDouble("temp");
            if ("F".equals(units.getString("temperature"))) {
                temp = (temp - 32d) * 5d / 9d;
            }
            String text = condition.getString("text");
            String code = condition.getString("code");
            String date = condition.getString("date");
            String sunrise = astronomy.getString("sunrise");
            String sunset = astronomy.getString("sunset");

            String owmCode = convertYahooCode(code, date, sunrise, sunset);

            if (location == null || location.isEmpty()) {
                location = channel.getJSONObject("location").getString("city");
            }

            return new WeatherResult(new WeatherData(temp, text, owmCode, latitude, longitude, location,
                    new Date(), Source.YAHOO), WeatherResult.ERROR_NONE, null, null);
        } finally {
            connection.disconnect();
        }
    } catch (Exception ex) {
        return new WeatherResult(null, WeatherResult.ERROR_THROWABLE, ex.getMessage(), ex);
    }
}

From source file:org.kuali.mobility.push.service.send.AndroidSendService.java

/**
 * Reads the response from the GCM server.
 * @param conn Connection to read the response from
 * @return The JSON formatted response from GCM
 *///  w  w w .j  av  a  2 s .co m
private static String readResponse(HttpsURLConnection conn) {
    InputStreamReader ir = null;
    String jsonResponse = null;
    try {
        jsonResponse = IOUtils.toString(conn.getInputStream());
    } catch (IOException e) {
        LOG.warn("Exception while trying to read input", e);
    } finally {
        IOUtils.closeQuietly(ir);
    }
    return jsonResponse;
}