嗨,我正在嘗試使用 HttpURLConnection 使用 HttpURLConnection 類將一些 POST 資料發送到服務器,如下所示,但它拋出“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();
}
}
}
uj5u.com熱心網友回復:
我相信問題是以下日志呼叫的結果:
logger.info("The header attribute:" conn.getHeaderFields());
HttpURLConnection#getHeaderFields繼承自URLConnectionwhich 將方法描述為回傳回應標頭(請參見此處)。
因此,我假設當您呼叫時conn.getHeaderFields(),HttpURLConnection連接并回傳回應頭欄位。由于連接已經建立,這會阻止您編輯連接的請求屬性 - 導致您遇到錯誤。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/414439.html
標籤:
