Yar
Yar

Reputation: 16

How to implement getResponseMessage() / getResponseCode for Android HttpURLConnection

I'm making get and post requests to an HTTP server. Everything seems to work well but I need to get the status code from the response message. Here is my post request

 postToHttp(URL url) throws IOException {

    StringBuilder stringBuilder = new StringBuilder();
    DataOutputStream dataOutputStream = null;
    Log.i(TAG , "calling :: " + url.toString());

    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setRequestMethod("POST");
    urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
    urlConnection.setRequestProperty("Accept", "application/json");
    urlConnection.setDoOutput(true);
    urlConnection.setDoInput(true);


    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject.put("city", "NYC");
        jsonObject.put("country", "USA");

        Log.i(TAG, "JSON onj :: " + jsonObject.toString());

         dataOutputStream = new DataOutputStream(urlConnection.getOutputStream());
        dataOutputStream.writeBytes(jsonObject.toString());

    } catch (JSONException e) {
        e.printStackTrace();
    }finally {
        dataOutputStream.flush();
        dataOutputStream.close();
    }

    //Need to check the post status?


}

Upvotes: 0

Views: 112

Answers (1)

Gabe Sechan
Gabe Sechan

Reputation: 93542

Just call urlConnection.getResponseCode()

Upvotes: 1

Related Questions