1

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:

enter image description here

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.

2
  • 1
    You can use getErrorStream() of HttpURLConnection. Commented Aug 23, 2017 at 3:13
  • There will not be a catch as a json text is returned as you said. Commented Aug 23, 2017 at 7:28

1 Answer 1

2

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.
Sign up to request clarification or add additional context in comments.

1 Comment

You should use readLine() instead of calling a function for every char.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.