Java Http请求中的错误消息
我使用下面的代码发出http请求,但当抛出异常时,我无法获取每个字段的错误消息。在postman中,它确实显示了正确的错误消息:Java Http请求中的错误消息,java,Java,我使用下面的代码发出http请求,但当抛出异常时,我无法获取每个字段的错误消息。在postman中,它确实显示了正确的错误消息: HttpsURLConnection con = (HttpsURLConnection) new URL(url).openConnection(); con.setSSLSocketFactory(sc.getSocketFactory()); con.setDoOutput(true); con.setRequestProper
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
”
而《邮差》则显示:
{
"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();
希望这能有所帮助 你是从邮递员那里复制的吗?还是发送邮递员的请求图片代码的输出是什么,它是执行try block还是最终捕获exceptionsank。我试试看。