[英]Why does Content-Length HTTP header field use a value other than the one given in Java code?
我有一段Java代碼將字節數組傳輸到HTTP服務器:
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary="
+ myBoundary);
connection.setRequestProperty("Content-Length", 1024);
我使用此代碼傳輸大小大於1024的字節數組。它運行良好。 但實際的HTTP消息(由Wireshark捕獲)顯示Content-Length的值是實際大小而不是1024.為什么?
我在HTTP規范中搜索但沒有發現任何提示。 我沒有使用任何Transfer-Encoding或Transfer-coding。
我猜HttpURLConnection
將簡單地用正確的值覆蓋Content-Length
標頭,因為它知道說謊它是不好的;-)
確實如此:在sun.net.www.protocol.HttpURLConnection
第535-550行,如果合適,設置Content-Length
。 這在用戶指定的標頭設置后發生,因此該值將被覆蓋。
這是正確的:如果您傳輸的數據量與聲明的數量不符,那么您只會混淆另一端。
檢查sun.net.www.protocol.http.HttpURLConnection
的源代碼似乎有一個受限制的標頭列表,在調用setRequestProperty
時將被忽略。 Content-Length
就在該列表中。 不幸的是,這似乎沒有記錄(至少我找不到任何關於此的文檔,只討論相關問題 )。
谷歌搜索引入此“功能”的ChangeSet中提到的錯誤ID(?),似乎此更改是作為對安全漏洞CVE-2010-3541和CVE-2010-3573 ( 本主題的Redhat錯誤 )的反應而引入的。
通過在JVM啟動時將系統屬性sun.net.http.allowRestrictedHeaders
設置為true
,可以手動禁用該限制。
這解決了我:
connection.setFixedLengthStreamingMode(myString.getBytes().length);
conn.setRequestProperty("Content-length", String.valueOf(myString.getBytes().length));
“connection.setFixedLengthStreamingMode(myString.getBytes()的長度。);” 在設置Content-Length標頭之前。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.