Harish Algat
Harish Algat

Reputation: 27

Http Request using java.net.* package

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?

Upvotes: 1

Views: 176

Answers (1)

Rob Spoor
Rob Spoor

Reputation: 9110

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.

Upvotes: 2

Related Questions