Phate
Phate

Reputation: 6602

URL connection: how to get body returned with status != 200?

I have a webservice returning, sometimes, status 401. It comes with a JSON body, something like:

{"status": { "message" : "Access Denied", "status_code":"401"}}

Now, this is the code I'm using to make server requests:

HttpURLConnection conn = null;
try{
   URL url = new URL(/* url */);
   conn = (HttpURLConnection)url.openConnection(); //this can give 401
   JsonReader reader = new JsonReader(new InputStreamReader(conn.getInputStream()));

   JsonObject response = gson.fromJson(reader, JsonObject.class);
   //response handling
}catch(IOException ex){
       System.out.println(conn.getResponseMessage()); //not working
}

When request fails I'd like to read that json body, however getResponseMessage just gives me a generic "Unauthorized"...so how to retrieve that JSON?

Upvotes: 1

Views: 1779

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520878

You can call conn.getErrorStream() in the case of a non 200 response:

HttpURLConnection conn = null;
try {
    URL url = new URL(/* url */);
    conn = (HttpURLConnection)url.openConnection(); //this can give 401
    JsonReader reader = new JsonReader(new InputStreamReader(conn.getInputStream()));

    JsonObject response = gson.fromJson(reader, JsonObject.class);
} catch(IOException ex) {
    JsonReader reader = new JsonReader(new InputStreamReader(conn.getErrorStream()));
    JsonObject response = gson.fromJson(reader, JsonObject.class);
}

Doing a cursory search through the Stack Overflow database would have brought you to this article which mentions this solution.

Upvotes: 1

Related Questions