Example usage for javax.net.ssl HttpsURLConnection getResponseCode

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

Introduction

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

Prototype

public int getResponseCode() throws IOException 

Source Link

Document

Gets the status code from an HTTP response message.

Usage

From source file:com.photon.phresco.nativeapp.eshop.net.NetworkManager.java

public static boolean checkHttpsURLStatus(final String url) {
    boolean https_StatusFlag = false;
    System.out.println("Entered in checkHttpsURLStatus >>>>>>>>>>>>>>>");

    URL httpsurl;//from w  ww. j  ava2  s .  com
    try {

        // Create a context that doesn't check certificates.
        SSLContext ssl_ctx = SSLContext.getInstance("TLS");
        TrustManager[] trust_mgr = get_trust_mgr();
        ssl_ctx.init(null, // key manager
                trust_mgr, // trust manager
                new SecureRandom()); // random number generator
        HttpsURLConnection.setDefaultSSLSocketFactory(ssl_ctx.getSocketFactory());
        System.out.println("Url =========" + url);
        httpsurl = new URL(url);

        HttpsURLConnection con = (HttpsURLConnection) httpsurl.openConnection();
        con.setHostnameVerifier(DO_NOT_VERIFY);
        int statusCode = con.getResponseCode();
        System.out.println("statusCode =========" + statusCode);

        if (statusCode == HttpURLConnection.HTTP_OK) {

            https_StatusFlag = true;

        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }

    return https_StatusFlag;
}

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 v a  2 s. c o  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.streamsets.datacollector.http.SlaveWebServerTaskIT.java

private static void verifyWebServerTask(final WebServerTask ws, SlaveRuntimeInfo runtimeInfo) throws Exception {
    try {/*  ww w . j  a v  a  2s.c o  m*/
        ws.initTask();
        new Thread() {
            @Override
            public void run() {
                ws.runTask();
            }
        }.start();
        waitForStart(ws);
        HttpsURLConnection conn = (HttpsURLConnection) new URL(
                "https://127.0.0.1:" + ws.getServerURI().getPort() + "/ping").openConnection();
        TestWebServerTaskHttpHttps.configureHttpsUrlConnection(conn);
        Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
        Assert.assertNotNull(runtimeInfo.getSSLContext());
    } finally {
        ws.stopTask();
    }
}

From source file:com.rmtheis.yandtran.YandexTranslatorAPI.java

/**
 * Forms an HTTPS request, sends it using GET method and returns the result of the request as a String.
 * /*from  ww  w .j av  a  2  s.co m*/
 * @param url The URL to query for a String response.
 * @return The translated String.
 * @throws Exception on error.
 */
private static String retrieveResponse(final URL url) throws Exception {
    final HttpsURLConnection uc = (HttpsURLConnection) url.openConnection();
    if (referrer != null)
        uc.setRequestProperty("referer", referrer);
    uc.setRequestProperty("Content-Type", "text/plain; charset=" + ENCODING);
    uc.setRequestProperty("Accept-Charset", ENCODING);
    uc.setRequestMethod("GET");

    try {
        final int responseCode = uc.getResponseCode();
        final String result = inputStreamToString(uc.getInputStream());
        if (responseCode != 200) {
            throw new Exception("Error from Yandex API: " + result);
        }
        return result;
    } finally {
        if (uc != null) {
            uc.disconnect();
        }
    }
}

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

public static Worksheet createWorksheet(Spreadsheet spreadsheet, String title, int row, int col,
        String authToken) throws Exception {
    URL url = new URL("https://spreadsheets.google.com/feeds/worksheets/" + spreadsheet.getId()
            + "/private/full?access_token=" + authToken);

    String payload = "<entry xmlns=\"http://www.w3.org/2005/Atom\""
            + " xmlns:gs=\"http://schemas.google.com/spreadsheets/2006\">" + "<title>"
            + URLEncoder.encode(title, "UTF-8") + "</title>" + "<gs:rowCount>" + row + "</gs:rowCount>"
            + "<gs:colCount>" + col + "</gs:colCount>" + "</entry>";

    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setDoInput(true);//from   w w w.ja  v a 2  s  . co  m
    conn.setDoOutput(true);
    conn.addRequestProperty("Content-Type", "application/atom+xml");
    conn.addRequestProperty("Content-Length", "" + payload.getBytes("UTF-8").length);
    OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
    out.write(payload);
    out.close();

    if (conn.getResponseCode() / 100 >= 3) {
        String s = new String(IOUtils.toByteArray(conn.getErrorStream()));
        throw new Exception(s);
    }

    List<Worksheet> worksheets = getWorksheets(spreadsheet, authToken);
    for (Worksheet worksheet : worksheets) {
        if (title.equals(worksheet.getTitle())) {
            return worksheet;
        }
    }
    throw new IllegalStateException("Worksheet lookup failed. Worksheet is not created properly.");
}

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.dmsl.anyplace.utils.NetworkUtils.java

public static InputStream downloadHttps(String urlS) throws IOException, URISyntaxException {
    InputStream is = null;/*from   w  w  w . ja v a 2s  .co m*/

    URL url = new URL(encodeURL(urlS));

    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setReadTimeout(10000);
    conn.setConnectTimeout(15000);
    conn.setRequestMethod("GET");
    conn.setDoInput(true);

    conn.connect();

    int response = conn.getResponseCode();
    if (response == 200) {
        is = conn.getInputStream();
    }

    return is;
}

From source file:au.id.micolous.frogjump.Util.java

public static void updateCheck(final Activity activity) {
    (new AsyncTask<Void, Void, Boolean>() {
        @Override//ww  w . j a  va  2 s. c om
        protected Boolean doInBackground(Void... voids) {
            try {
                String my_version = Integer.toString(getVersionCode());
                URL url = new URL("https://micolous.github.io/frogjump/version.json");
                HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setDoInput(true);
                conn.setReadTimeout(10000);
                conn.setConnectTimeout(15000);
                conn.connect();

                int responseCode = conn.getResponseCode();
                if (responseCode == 200) {
                    InputStream is = conn.getInputStream();
                    byte[] buffer = new byte[1024];
                    if (is.read(buffer) == 0) {
                        Log.i(TAG, "Error reading update file, 0 bytes");
                        return false;
                    }
                    JSONObject root = (JSONObject) new JSONTokener(new String(buffer, "US-ASCII")).nextValue();

                    if (root.has(my_version)) {
                        if (root.getBoolean(my_version)) {
                            // Definitely needs update.
                            Log.i(TAG, "New version required, explicit flag.");
                            return true;
                        }
                    } else {
                        // unlisted version, assume it is old.
                        Log.i(TAG, "New version required, not in list.");
                        return true;
                    }

                }
            } catch (Exception ex) {
                Log.e(TAG, "Error getting update info", ex);
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean needsUpdate) {
            if (needsUpdate)
                newVersionAlert(activity);
        }
    }).execute();
}

From source file:com.versobit.weatherdoge.WeatherUtil.java

private static WeatherResult getWeatherFromYahoo(double latitude, double longitude, String location) {
    try {//from   ww  w .  jav a 2 s. c o  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.liberty.android.fantastischmemo.downloader.google.FolderFactory.java

public static void addDocumentToFolder(Document document, Folder folder, String authToken)
        throws XmlPullParserException, IOException {
    URL url = new URL("https://www.googleapis.com/drive/v2/files/" + document.getId() + "/parents");

    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setDoInput(true);//  w w w . j  a va 2  s  . com
    conn.setDoOutput(true);
    conn.setRequestProperty("Authorization", "Bearer " + authToken);
    conn.setRequestProperty("Content-Type", "application/json");

    String payload = "{\"id\":\"" + folder.getId() + "\"}";
    conn.setRequestProperty("Content-Length", "" + payload.length());

    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(conn.getOutputStream());
    outputStreamWriter.write(payload);
    outputStreamWriter.close();

    if (conn.getResponseCode() / 100 >= 3) {
        String s = new String(IOUtils.toByteArray(conn.getErrorStream()));
        throw new RuntimeException(s);
    }
}