This is my situation. I am calling the web authentication API with POST message. Upon success, it returns a token. Otherwise, it returns error message (json) specifying reasons (eg: "incorrect password", "account lock", etc
), with response code 400, etc
.
Sample error viewed from browser:
So, I manage to call, get and return the success message, but not when there is an error. Here's the pseudo code (I omit the redundant part. Basically focus on the 'catch' scope):
HttpURLConnection conn = null; //Must define outside as null?
try {
...
byte[] postDataBytes = ...
URL url = new URL(urlLogin);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod( "POST" );
...
conn.getOutputStream().write(postDataBytes);
Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
StringBuilder sb = new StringBuilder();
for (int c; (c = in.read()) >= 0;)
sb.append((char)c);
String response = sb.toString(); // Yeah I got this
return response;
}
catch(IOException ex){
//the variable ex doesn't tell anything about the response code
//neither the response message
//so i access the conn to get
//
try {
int responseCode = conn.getResponseCode();
return "code: " + responseCode; //somehow this line just doesn't work!
}
catch (Exception ex2){
}
}
To elaborate a bit, the IOException
doesn't tell anything about the response. So I access the HttpURLConnection
variable.
The
conn.getResponseCode() does return 400
,
conn.getResponseMessage() does return "Bad Request"
, but NOT the error json message from server.
Any idea?
EDIT:
I just want to know, what is the correct way to get the response code/message during Exception/error.
getErrorStream()
of HttpUrlConnection
is probably what you are looking for.
Reader in = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
// Do you response parsing here.