Java Android如何在Exception中获取HTTPUrlConnection(POST)响应代码和消息?

时间:2017-08-23 02:53:28

标签: java android exception httpurlconnection http-response-codes

这是我的情况。我正在使用POST消息调用Web身份验证API。成功后,它会返回一个令牌。否则,它返回错误消息(json),指定原因(例如:"incorrect password", "account lock", etc),响应代码为400, etc

从浏览器查看示例错误:

enter image description here

所以,我设法调用,获取并返回成功消息,但不是在出现错误时。这是伪代码(我省略了冗余部分。基本上关注'catch'范围):

    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){
        }
    }

为了详细说明,IOException没有说明响应。所以我访问了HttpURLConnection变量。

conn.getResponseCode() does return 400

conn.getResponseMessage() does return "Bad Request",但不是来自服务器的错误json消息。

有什么想法吗?

修改

我只想知道,在异常/错误期间获取响应代码/消息的正确方法是什么。

1 个答案:

答案 0 :(得分:1)

getErrorStream()的{​​{1}}可能就是你要找的东西。

HttpUrlConnection