gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 00:23:35 28 4
gpt4 key购买 nike

这是我的情况。我正在使用 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com