[英]How to capture error response body and error code in post call where the response is not 200 via java code?
I am writing the below code, but that is only capturing response body when response code is 200. For all other occasions it is failing.我正在编写以下代码,但这仅在响应代码为 200 时捕获响应主体。对于所有其他情况,它都失败了。
Picture - postman post call and response where response code is not equal to 200图片 - postman 发布呼叫和响应,其中响应代码不等于 200
For example when response code 409, the code is throwing error with例如,当响应代码 409 时,代码会抛出错误
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 409 for URL: http://fetch.product/v1/products/PD16798270/validate at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1919) at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1515) at com.Main.main(Main.java:58) Exception in thread "main" java.io.IOException: Server returned HTTP response code: 409 for URL: http://fetch.product/v1/products/PD16798270/validate at java.base/sun.net.www.protocol. http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1919) at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1515) at com.Main.main(Main.java:58)
Code I am using below -我在下面使用的代码 -
public static void main(String[] args) throws Exception {
String url = "http://fetch.product/v1/products/PD16798270/validate";
URL u = new URL(url);
StringBuilder postData = new StringBuilder();
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
HttpURLConnection conn = (HttpURLConnection)u.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
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();
System.out.println(response);
}
If the request returns an error response, you can read it from the connection's "error stream".如果请求返回错误响应,您可以从连接的“错误流”中读取它。 For example, this would read the body whether the request returned success or error:
例如,这将读取请求是否返回成功或错误的正文:
InputStream input;
if (conn.getResponseCode() >= 400) {
input = conn.getErrorStream();
} else {
input = conn.getInputStream();
}
Reader in = new BufferedReader(new InputStreamReader(input, "UTF-8"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.