我正在使用下面的代码发出http请求,但是当抛出异常时,我无法获取每个字段的错误消息。在 postman 中,它确实显示了正确的错误消息:
HttpsURLConnection con = (HttpsURLConnection) new URL(url).openConnection();
con.setSSLSocketFactory(sc.getSocketFactory());
con.setDoOutput(true);
con.setRequestProperty("Authorization","Basic KEY")
con.setRequestProperty("Content-Length", Integer.toString(data.length()));
try {
con.getOutputStream().write(data.getBytes("UTF-8"));
final BufferedReader rd = new BufferedReader(new InputStreamReader(con.getInputStream()));
stringBuffer = new StringBuffer();
while ((line = rd.readLine()) != null) {
stringBuffer.append(line);
}
rd.close();
}catch(Exception e){
println stringBuffer.toString()
throw new Exception("Some error occurred " + e.message)
}
它只是显示消息“服务器返回了 URL 的 HTTP 响应代码:422:https://test.api.promisepay.com/users/35
”
而在 Postman 中它显示:
{
"errors": {
"mobile": [
"already exists"
]
}
}
最佳答案
您无法使用输入流读取错误,而是应该使用错误流来实现此目的。
下面是一个示例片段:
将数据写入输出流后,您应该检查返回的响应代码:
int respCode = con.getResponseCode();
然后检查返回的响应码是否为200,如果不是则出现错误:
InputStream is=null;
if(respCode==200){
is = con.getInputStream();
} else if (urlConnection.getErrorStream() != null) {
is = con.getErrorStream();
}
现在您可以更改代码来读取错误:
final BufferedReader rd = new BufferedReader(new
InputStreamReader(is));
stringBuffer = new StringBuffer();
while ((line = rd.readLine()) != null) {
stringBuffer.append(line);
}
rd.close();
希望这会有所帮助!
关于java - Http 请求中的错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47901877/