1

I am firing API calls through java package java.net.* But, for 400 and above Responses I am not getting the response body. So Not able to figure out why the call is failing.

Below snippet fires the call.

public static String sendPostRequest(String requestUrl, String payload, Map<String, String> requestProperties) {
        StringBuffer jsonString = new StringBuffer();
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            Set<String> keys = requestProperties.keySet();
            for (String property : keys) {
                connection.setRequestProperty(property, requestProperties.get(property));
            }
            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8);
            writer.write(payload);
            writer.close();
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = br.readLine()) != null) {
                jsonString.append(line);
            }
            br.close();
            connection.disconnect();
            //  System.out.println("response  " + jsonString.toString());

        } catch (Exception e) {
            log.error("Error for call " + requestUrl);
            log.error(e.getMessage());
        }
        return jsonString.toString();
    }

Is there any work around?

1 Answer 1

2

For responses with status codes 400 and higher you need to use connection.getErrorStream(). Calling connection.getOutputStream() will throw an exception. You can use connection.getResponseCode() before calling connection.getOutputStream() or connection.getErrorStream() to determine the status, and therefore which of the two methods to use.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.