1

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);
     
}

1 Answers1

2

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"));
Joni
  • 108,737
  • 14
  • 143
  • 193
  • This is working absolutely fine man !!!... Saved my day. The o/p is now coming properly as below - { "state" : "Created", "errors" : [ { "code" : "ARTICLE_HAS_NO_AUTHORS", "category" : "Article" } ] } Can you help me how to segregate the part - "ARTICLE_HAS_NO_AUTHORS" from error response ? I want only ARTICLE_HAS_NO_AUTHORS in the java code o/p. – Moinak Banerjee Jul 17 '20 at 04:20
  • That data format is called JSON, it's best to use a library to parse it: https://stackoverflow.com/questions/2591098/how-to-parse-json-in-java – Joni Jul 17 '20 at 10:52