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

标签 java android exception httpurlconnection http-response-codes

这是我的情况。我正在使用 POST 消息调用 Web 身份验证 API。成功后,它返回一个 token 。否则,它返回错误消息 (json) 指定原因(例如:“不正确的密码”、“帐户锁定”等),以及响应代码 400 等

从浏览器查看的示例错误:

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() 返回 400,

conn.getResponseMessage() 确实返回“Bad Request”,但不是来自服务器的错误 json 消息。

有什么想法吗?

编辑:

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

最佳答案

HttpUrlConnection

getErrorStream() 可能就是您要查找的内容。

    Reader in = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));

    // Do you response parsing here.

关于Java Android 如何在Exception 中获取HTTPUrlConnection (POST) 响应代码和消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45829905/

相关文章:

javascript - 使用函数设置变量值的单行代码,如果为假则抛出异常

python - 为什么建议从 Exception 派生而不是 Python 中的 BaseException 类?

c# - Web异常: Unable to connect to the remote server

java - 如何在客户端查看JSP文件的来源

android - 在 AppCompat 主题中设置标题颜色

java - 将应用程序迁移到 Java 7 的动机和动机

android - Android 中的消息和电子邮件 Intent ?

android - 如何将字符串传递到 onItemClick ListView 中?

java - Android:三星 S2 上的 GLES 2.0 损坏?

java - React Native 运行 android Build 失败并出现异常