Skip to content
Advertisement

Exception : java.lang.IllegalStateException: Already connected

Hi I’m trying to use HttpURLConnection to send some POST data to a server using the HttpURLConnection class as shown below but it is throwing “java.lang.IllegalStateException: Already connected.” at the code – conn.setRequestProperty(eachEntry.getKey(), eachEntry.getValue()); in the below code. Can any one pls suggest what mistake I am doing here. Also the similar .setRequestPorperty, I am using in other places and it is fine but only when iterating list of request property inside the loop, facing this issue as here.

public boolean createAsyncPostRestConnection(boolean isdatabagAvailable, Map<String, Object> databag, String lbrurl,
                                             String apiURL, String componentName, HashMap<String, String> requestProperty) {
    HttpURLConnection conn = null;
    try {
        // This check is when we have the databag but it is empty. Databag is not mandatory to invoke this function.
        if (isdatabagAvailable && databag.isEmpty()) {
            logger.error("Databag is empty.");
            return false;
        }
        lbrurl = ContentPatchUtils.removeSlash(lbrurl);
        URL url = new URL(lbrurl + apiURL);
        conn = podConfigUtil.getUrlConnection(url);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("charset", "UTF-8");
        conn.setRequestProperty(Constants.AUTHRORIZATION, BaseUtil.getPrivateAPIAuthHeader());
        logger.info("The header attribute:" + conn.getHeaderFields());

        if (!requestProperty.isEmpty()) {
            logger.info("Setting the request property now." + requestProperty);
            for (Map.Entry<String, String> eachEntry : requestProperty.entrySet()) {
                logger.info("eachEntry.getKey():"+ eachEntry.getKey() +",eachEntry.getValue():"+eachEntry.getValue());
                conn.setRequestProperty(eachEntry.getKey(), eachEntry.getValue());
            }
        }


        conn.setDoOutput(true);
        logger.info("The URL formed is :" + conn.getURL());
        JSONObject payload = new JSONObject(databag);
        try (OutputStream os = conn.getOutputStream()) {
            byte[] input = payload.toString().getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }
        logger.info("Harish,OutputStream write is done.");
        if (conn.getResponseCode() == HttpURLConnection.HTTP_ACCEPTED) {
            logger.info(componentName + " ,is invoked successfully.");
            return true;

        } else {
            logger.info(componentName + ",API invocation failed. " +
                    "HTTP code: " + conn.getResponseCode() + ";" +
                    "Response Message: " + conn.getResponseMessage() + ";");
            return false;
        }

    }catch (Exception e) {
        logger.error("Connection could not be created. The exception trace is ", e);
        return false;
    } finally {
        if (conn != null) {
            logger.info("disconnecting the connection ");
            conn.disconnect();
        }
    }
}

Advertisement

Answer

I believe the problem is a result of the following log call:

logger.info("The header attribute:" + conn.getHeaderFields());

HttpURLConnection#getHeaderFields is inherited from URLConnection which describes the method as returning the response headers (see here).

Therefore, I assume when you call conn.getHeaderFields(), the HttpURLConnection connects and returns you the response header fields. This stops you from being able to edit the request properties of the connection as the connection has already been established – resulting in the error you are experiencing.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement