If the request is correct, then everything is fine, but if there is any parameter with an error, then when I try to pull out an InputStream, I catch an exception. While Postman perfectly displays the response body even if the request is incorrect. Tell me how you can count the answer?

public String post(String address, String request) { String response = ""; try { URL obj = new URL(address); HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Authorization", authorization); con.setRequestProperty("Content-Type", "application/json"); con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(request); wr.flush(); wr.close(); BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream())); String line; while ((line = in.readLine()) != null) { response += line; } in.close(); } catch (IOException e) { logger.error("HttpsRequestHandler error: " + e.getMessage()); return null; } return response; } 

Error - IOException

  • one
    ловлю exception - what? - post_zeew
  • @post_zeew IOException - mr. Ball
  • Show stack stack. - post_zeew

1 answer 1

For errors, a separate thread:

 HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); InputStream errorStream = con.getErrorStream(); 

It is done in different ways, you can:

 if (httpConn.getResponseCode() == 200){ InputStream is = con.getInputStream(); } else { InputStream is = con.getErrorStream(); } 

It is possible so:

 HttpsURLConnection con = null; try { //... con = (HttpsURLConnection) obj.openConnection(); BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream())); //... } catch (IOException e) { InputStream is = con.getErrorStream(); //... logger.error("HttpsRequestHandler error: " + e.getMessage()); return null; } 

You can still somehow as you like.