【问题标题】:Java Android How to get HTTPUrlConnection (POST) response code and message in the Exception?Java Android 如何在异常中获取 HTTPUrlConnection (POST) 响应代码和消息?
【发布时间】:2017-08-23 02:53:28
【问题描述】:

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

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

所以,我设法调用、获取并返回成功消息,但在出现错误时却不行。这是伪代码(我省略了多余的部分。主要关注“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 消息。

有什么想法吗?

编辑:

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

【问题讨论】:

  • 可以使用HttpURLConnection的getErrorStream()
  • 不会有问题,因为如您所说,返回 json 文本。

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


【解决方案1】:

HttpUrlConnection 中的getErrorStream() 可能就是您要找的。​​p>

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

    // Do you response parsing here.

【讨论】:

  • 你应该使用 readLine() 而不是为每个字符调用一个函数。
猜你喜欢
  • 2012-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-20
  • 2019-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多