【发布时间】:2020-11-06 16:39:26
【问题描述】:
我正在编写下面的代码,但这只是在响应代码为 200 时捕获响应正文。对于所有其他情况,它都失败了。
图片 - postman post call and response where response code is not equal to 200
例如,当响应代码为 409 时,代码会抛出错误
线程“main”java.io.IOException 中的异常:服务器返回 HTTP 响应代码:409 用于 URL:http://fetch.product/v1/products/PD16798270/validate 在 java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1919) 在 java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1515) 在 com.Main.main(Main.java:58)
我在下面使用的代码 -
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);
}
【问题讨论】:
标签: java post http-post postman