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.
Picture - postman post call and response where response code is not equal to 200
For example when response code 409, the code is throwing error with
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);
}