我正在使用下面的代码来发出http请求,但是当抛出异常时,我无法获取每个字段的错误消息。邮递员确实显示了正确的错误信息:
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)
}
它只是显示消息" Server returned HTTP response code: 422 for URL: https://test.api.promisepay.com/users/35
"
而在Postman中它显示:
{
"errors": {
"mobile": [
"already exists"
]
}
}
答案 0 :(得分:1)
您无法使用输入流读取错误,而应使用错误流来实现此目的。
以下是一个示例代码段:
将数据写入输出流后,您应该检查返回的响应代码:
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();
希望这可能有所帮助!