Example usage for java.net HttpURLConnection getResponseCode

List of usage examples for java.net HttpURLConnection getResponseCode

Introduction

In this page you can find the example usage for java.net HttpURLConnection getResponseCode.

Prototype

public int getResponseCode() throws IOException 

Source Link

Document

Gets the status code from an HTTP response message.

Usage

From source file:com.smashedin.facebook.AbstractGetNameTask.java

/**
 * Contacts the user info server to get the profile of the user and extracts the first name
 * of the user from the profile. In order to authenticate with the user info server the method
 * first fetches an access token from Google Play services.
 * @throws IOException if communication with user info server failed.
 * @throws JSONException if the response from the server could not be parsed.
 *//*  w  w  w  .  j av  a  2 s .  c o  m*/
private void fetchNameFromProfileServer() throws IOException, JSONException {
    String token = fetchToken();
    if (token == null) {
        // error has already been handled in fetchToken()
        return;
    }
    mActivity.AuthenticateGoogleFromSmashed(token);
    URL url = new URL("https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + token);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    int sc = con.getResponseCode();
    if (sc == 200) {
        InputStream is = con.getInputStream();
        String name = getFirstName(readResponse(is));
        mActivity.show("Hello " + name + "!");
        is.close();
        return;
    } else if (sc == 401) {
        GoogleAuthUtil.invalidateToken(mActivity, token);
        onError("Server auth error, please try again.", null);
        Log.i(TAG, "Server auth error: " + readResponse(con.getErrorStream()));
        return;
    } else {
        onError("Server returned the following error code: " + sc, null);
        return;
    }
}

From source file:net.mceoin.cominghome.api.NestUtil.java

private static String getNestAwayStatusCall(String access_token) {

    String away_status = "";

    String urlString = "https://developer-api.nest.com/structures?auth=" + access_token;
    log.info("url=" + urlString);

    StringBuilder builder = new StringBuilder();
    boolean error = false;
    String errorResult = "";

    HttpURLConnection urlConnection = null;
    try {/*from  w  w w  .ja  v a 2  s .  c  o  m*/
        URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestProperty("User-Agent", "ComingHomeBackend/1.0");
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setConnectTimeout(15000);
        urlConnection.setReadTimeout(15000);
        //            urlConnection.setChunkedStreamingMode(0);

        //            urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf8");

        boolean redirect = false;

        // normally, 3xx is redirect
        int status = urlConnection.getResponseCode();
        if (status != HttpURLConnection.HTTP_OK) {
            if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                    || status == 307 // Temporary redirect
                    || status == HttpURLConnection.HTTP_SEE_OTHER)
                redirect = true;
        }

        //            System.out.println("Response Code ... " + status);

        if (redirect) {

            // get redirect url from "location" header field
            String newUrl = urlConnection.getHeaderField("Location");

            // open the new connnection again
            urlConnection = (HttpURLConnection) new URL(newUrl).openConnection();
            urlConnection.setRequestMethod("PUT");
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            //                urlConnection.setChunkedStreamingMode(0);

            //                System.out.println("Redirect to URL : " + newUrl);

        }

        int statusCode = urlConnection.getResponseCode();

        log.info("statusCode=" + statusCode);
        if ((statusCode == HttpURLConnection.HTTP_OK)) {
            error = false;

            InputStream response;
            response = urlConnection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(response));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            log.info("response=" + builder.toString());
            JSONObject object = new JSONObject(builder.toString());

            Iterator keys = object.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                JSONObject structure = object.getJSONObject(key);

                if (structure.has("away")) {
                    away_status = structure.getString("away");
                } else {
                    log.info("missing away");
                }
            }

        } else if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
            // bad auth
            error = true;
            errorResult = "Unauthorized";
        } else if (statusCode == HttpURLConnection.HTTP_BAD_REQUEST) {
            error = true;
            InputStream response;
            response = urlConnection.getErrorStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(response));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            log.info("response=" + builder.toString());
            JSONObject object = new JSONObject(builder.toString());

            Iterator keys = object.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                if (key.equals("error")) {
                    // error = Internal Error on bad structure_id
                    errorResult = object.getString("error");
                    log.info("errorResult=" + errorResult);
                }
            }
        } else {
            error = true;
            errorResult = Integer.toString(statusCode);
        }

    } catch (IOException e) {
        error = true;
        errorResult = e.getLocalizedMessage();
        log.warning("IOException: " + errorResult);
    } catch (Exception e) {
        error = true;
        errorResult = e.getLocalizedMessage();
        log.warning("Exception: " + errorResult);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }

    if (error)
        away_status = "Error: " + errorResult;
    return away_status;
}

From source file:com.example.test_fb_api.AbstractGetNameTask.java

/**
 * Contacts the user info server to get the profile of the user and extracts the first name
 * of the user from the profile. In order to authenticate with the user info server the method
 * first fetches an access token from Google Play services.
 * @throws IOException if communication with user info server failed.
 * @throws JSONException if the response from the server could not be parsed.
 *//*w  ww  .  j  av  a 2 s.c  om*/
private void fetchNameFromProfileServer() throws IOException, JSONException {
    String token = fetchToken();
    if (token == null) {
        // error has already been handled in fetchToken()
        return;
    }
    URL url = new URL("https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + token);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    int sc = con.getResponseCode();
    if (sc == 200) {
        InputStream is = con.getInputStream();
        String name = getFirstName(readResponse(is));
        mActivity.show("Hello " + name + "!" + token);
        Log.e(name, token);
        is.close();
        return;
    } else if (sc == 401) {
        GoogleAuthUtil.invalidateToken(mActivity, token);
        onError("Server auth error, please try again.", null);
        Log.i(TAG, "Server auth error: " + readResponse(con.getErrorStream()));
        return;
    } else {
        onError("Server returned the following error code: " + sc, null);
        return;
    }
}

From source file:com.ehsy.solr.util.SimplePostTool.java

private static boolean checkResponseCode(HttpURLConnection urlc) throws IOException {
    if (urlc.getResponseCode() >= 400) {
        warn("Solr returned an error #" + urlc.getResponseCode() + " (" + urlc.getResponseMessage()
                + ") for url: " + urlc.getURL());
        Charset charset = StandardCharsets.ISO_8859_1;
        final String contentType = urlc.getContentType();
        // code cloned from ContentStreamBase, but post.jar should be standalone!
        if (contentType != null) {
            int idx = contentType.toLowerCase(Locale.ROOT).indexOf("charset=");
            if (idx > 0) {
                charset = Charset.forName(contentType.substring(idx + "charset=".length()).trim());
            }//from www. j  av a 2 s.  co m
        }
        // Print the response returned by Solr
        try (InputStream errStream = urlc.getErrorStream()) {
            if (errStream != null) {
                BufferedReader br = new BufferedReader(new InputStreamReader(errStream, charset));
                final StringBuilder response = new StringBuilder("Response: ");
                int ch;
                while ((ch = br.read()) != -1) {
                    response.append((char) ch);
                }
                warn(response.toString().trim());
            }
        }
        return false;
    }
    return true;
}

From source file:com.alltivity.wotnow.AbstractGetNameTask.java

/**
 * Contacts the user info server to get the profile of the user and extracts
 * the first name of the user from the profile. In order to authenticate
 * with the user info server the method first fetches an access token from
 * Google Play services./*from w w  w.j a  v a2s . co  m*/
 * @return 
 * @return 
 * 
 * @throws IOException
 *             if communication with user info server failed.
 * @throws JSONException
 *             if the response from the server could not be parsed.
 */
private void fetchNameFromProfileServer() throws IOException, JSONException {
    String token = fetchToken();
    URL url = new URL("https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + token);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    int sc = con.getResponseCode();
    if (sc == 200) {
        InputStream is = con.getInputStream();
        GOOGLE_USER_DATA = readResponse(is);
        //Log.v("FetchGoogleProfile", GOOGLE_USER_DATA);
        is.close();
        emailId = mEmail;
        /*   Intent intent=new Intent(mActivity,NativeHandler.class);
           intent.putExtra("email_id", mEmail);
           mActivity.startActivity(intent);
           mActivity.finish();*/
        return;
    } else if (sc == 401) {
        GoogleAuthUtil.invalidateToken(mActivity, token);
        onError("Server auth error, please try again.", null);
        //Toast.makeText(mActivity, "Please try again", Toast.LENGTH_SHORT).show();
        //mActivity.finish();
        return;
    } else {
        onError("Server returned the following error code: " + sc, null);
        return;
    }
}

From source file:com.NotifyMe.auth.AbstractGetInfoTask.java

/**
 * Contacts the user info server to get the profile of the user and extracts the first name
 * of the user from the profile. In order to authenticate with the user info server the method
 * first fetches an access token from Google Play services.
 * @throws IOException if communication with user info server failed.
 * @throws JSONException if the response from the server could not be parsed.
 *//*from w w w  .  ja  v  a  2  s.  c  om*/
private void fetchNameFromProfileServer() throws IOException, JSONException {
    String token = fetchToken();
    if (token == null) {
        // error has already been handled in fetchToken()
        return;
    }
    URL url = new URL("https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + token);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    int sc = con.getResponseCode();
    if (sc == 200) {
        InputStream is = con.getInputStream();
        //String name = getFirstName(readResponse(is));
        //mActivity.show("Hello " + name + "!");
        mActivity.saveProfile(new JSONObject(readResponse(is)));
        is.close();
        mActivity.finishActivity();
        return;
    } else if (sc == 401) {
        GoogleAuthUtil.invalidateToken(mActivity, token);
        onError("Server auth error, please try again.", null);
        Log.i(TAG, "Server auth error: " + readResponse(con.getErrorStream()));
        return;
    } else {
        onError("Server returned the following error code: " + sc, null);
        return;
    }
}

From source file:com.symphony.jirabot.clients.QuandlClient.java

private JSONObject makeGetRequest(String endpoint, HashMap<String, Object> parameters) {

    String url = BASE_URL + endpoint + "?api_key=" + this.apiKey + mapToQueryString(parameters);

    try {//from w  w  w. j a v  a  2s.c om
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");

        int responseCode = con.getResponseCode();

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

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

        return new JSONObject(response.toString());
    } catch (MalformedURLException error) {
        throw new UnsupportedOperationException(error);
    } catch (IOException error) {
        throw new RuntimeException(error);
    } catch (JSONException error) {
        throw new RuntimeException(error);
    }
}

From source file:com.sound.app.auth.AbstractGetNameTask.java

/**
 * Contacts the user info server to get the profile of the user and extracts the first name
 * of the user from the profile. In order to authenticate with the user info server the method
 * first fetches an access token from Google Play services.
 * @throws java.io.IOException if communication with user info server failed.
 * @throws org.json.JSONException if the response from the server could not be parsed.
 *//*w w  w .j a v a2s . c o  m*/
private void fetchNameFromProfileServer() throws IOException, JSONException {
    String token = fetchToken();
    if (token == null) {
        // error has already been handled in fetchToken()
        return;
    }
    URL url = new URL("https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + token);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    int sc = con.getResponseCode();
    if (sc == 200) {
        InputStream is = con.getInputStream();

        Auth auth = getInfo(readResponse(is));
        mActivity.next(auth);
        is.close();

    } else if (sc == 401) {
        GoogleAuthUtil.invalidateToken(mActivity, token);
        onError("Server auth error, please try again.", null);
        Log.i(TAG, "Server auth error: " + readResponse(con.getErrorStream()));
        return;
    } else {
        onError("Server returned the following error code: " + sc, null);
        return;
    }
}

From source file:com.example.firstapp.AbstractGetNameTask.java

/**
 * Contacts the user info server to get the profile of the user and extracts
 * the first name of the user from the profile. In order to authenticate
 * with the user info server the method first fetches an access token from
 * Google Play services./* w w w.  ja v  a 2s  .  c  o  m*/
 * @return 
 * @return 
 * 
 * @throws IOException
 *             if communication with user info server failed.
 * @throws JSONException
 *             if the response from the server could not be parsed.
 */
private void fetchNameFromProfileServer() throws IOException, JSONException {
    String token = fetchToken();
    URL url = new URL("https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + token);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    int sc = con.getResponseCode();
    if (sc == 200) {
        InputStream is = con.getInputStream();
        GOOGLE_USER_DATA = readResponse(is);
        is.close();

        Intent intent = new Intent(mActivity, HomeActivity.class);
        Bundle b = new Bundle();
        b.putSerializable("object", ob);
        intent.putExtras(b);
        intent.putExtra("email_id", mEmail);
        mActivity.startActivity(intent);
        mActivity.finish();
        return;
    } else if (sc == 401) {
        GoogleAuthUtil.invalidateToken(mActivity, token);
        onError("Server auth error, please try again.", null);
        //Toast.makeText(mActivity, "Please try again", Toast.LENGTH_SHORT).show();
        //mActivity.finish();
        return;
    } else {
        onError("Server returned the following error code: " + sc, null);
        return;
    }
}

From source file:com.jooketechnologies.network.ServerUtilities.java

static JSONObject post(String endpoint, int action, Map<String, String> params) {
    URL url;//from w w w  .  ja  v a2 s  .co m
    try {
        url = new URL(endpoint);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + endpoint);
    }
    StringBuilder bodyBuilder = new StringBuilder();
    Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
    // constructs the POST body using the parameters
    while (iterator.hasNext()) {
        Entry<String, String> param = iterator.next();
        bodyBuilder.append(param.getKey()).append('=').append(param.getValue());
        if (iterator.hasNext()) {
            bodyBuilder.append('&');
        }
    }
    String body = bodyBuilder.toString();
    byte[] bytes = body.getBytes();
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setFixedLengthStreamingMode(bytes.length);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        // post the request
        OutputStream out = conn.getOutputStream();
        out.write(bytes);
        out.close();
        // handle the response

        int status = conn.getResponseCode();
        InputStream is = conn.getInputStream();
        if (status != 200) {
            if (conn != null) {
                conn.disconnect();
            }
        } else {
            JSONObject jsonObject = streamToString(is);
            return jsonObject;
        }
    } catch (IOException e) {

        e.printStackTrace();
    }
    return null;

}