异常:java.lang.IllegalStateException:已经连接

Exception : java.lang.IllegalStateException: Already connected

您好,我正在尝试使用 HttpURLConnection 将一些 POST 数据发送到使用 HttpURLConnection class 的服务器,如下所示,但它抛出“java.lang.IllegalStateException:已连接。 “在代码 - conn.setRequestProperty(eachEntry.getKey(), eachEntry.getValue()); 下面的代码中。任何人都可以建议我在这里犯了什么错误。还有类似的.setRequestPorperty,我在其他地方使用它很好,但只有在循环内迭代请求列表属性时,才会遇到这里的问题。

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();
        }
    }
}

我认为问题是以下日志调用的结果:

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

HttpURLConnection#getHeaderFields 继承自 URLConnection,它描述了返回 response headers (see here) 的方法。

因此,我假设当您调用 conn.getHeaderFields() 时,HttpURLConnection 连接并且 returns 您响应 header 字段。这会阻止您编辑连接的请求属性,因为连接已经建立 - 导致您遇到错误。