1

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?

Phate
  • 6,066
  • 15
  • 73
  • 138
  • Where is the code you are using to read in the case where the response status is 200? I don't see that anywhere. – Tim Biegeleisen Aug 18 '15 at 13:17
  • First try the webservice url in any of the webservice tool like SOAPUI and identify the response for the given request – Nivetha T Aug 18 '15 at 13:21
  • Added code to handle response in case status is 200...problem is not the response, problem is the fact that apparently java.net.URL has no way to retrieve response body in case of return code !=200.. – Phate Aug 18 '15 at 13:24

1 Answers1

1

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.

Community
  • 1
  • 1
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360