HttpURLConnection: how to read a payload of 400 responses

I use the following code to send a JSON request to my web service, and for a bad request, I return a 400 message code along with a detailed JSON error response in the payload.

I do not understand how I could extract this payload on the client side when using HttpURLConnection, since it immediately throws IOException, and the connection InputStream- null.

HttpURLConnection connection = this.connect(url);
connection.setRequestMethod(method);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(jsonMessage);
InputStream is = null;
try {
    is = connection.getInputStream(); // IOException is thrown, how can I still get payload??
} catch (Exception e) {
} 
String response = getStringFromInputStream(is);

Also tried using getErrorStream(), but it contained the default Apache Tomcat error page, and not the payload that I see, for example, I use the visual REST API client.

+4

Source: https://habr.com/ru/post/1548144/


All Articles