![](/img/trans.png)
[英]Why does Content-Length HTTP header field use a value other than the one given in Java code?
[英]Java Http - Post Header Content-Length
我的 http-headers 有問題。 我需要發送一個帶有空正文和標題“Content-Length:0”的后請求。 但這似乎是不可能的,因為我得到了這個例外:
--org.apache.http.ProtocolException: Content-Length 標頭已經存在--
但是當我不包含標頭時,請求中沒有 Content-Length 標頭,因此我得到 400:錯誤請求。 我也用 Python 構建了它,它工作正常,但我不能讓它在 java 中工作。 你能幫我嗎?
這是我的代碼:
HttpClient client = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader(header..);
httpPost.addHeader(another header);
httpPost.addHeader("Content-Type","application/xml");
httpPost.addHeader("Content-Length","0");
httpPost.addHeader(another header);
HttpResponse response = client.execute(httpPost);
System.out.println(response.getStatusLine().getStatusCode());
編輯:
用@Beno Arakelyan 的回答解決了這個問題。
您不需要計算內容長度,客戶端將為您處理。 嘗試刪除標題並設置一個正文,例如: httpPost.setEntity(new StringEntity(""))
。
我試圖通過HTTP請求發送Content-Length
, 該請求基於apache http客戶端構建。 工作正常。 例:
private static final HttpRequest<?> HTTP_REQUEST =
HttpRequestBuilder.createGet(YOUR_URI)
.addDefaultHeader(HttpHeaders.CONTENT_LENGTH, "0")
.build();
public void test(){
System.out.println(HTTP_REQUEST.execute().getStatisCode()); // is 200
}
URL url = new URL("https://reqbin.com/echo/post/json");
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setRequestMethod("POST");
http.setDoOutput(true);
http.setRequestProperty("Content-Type", "application/json");
String data = "{\"widget\": {\n \"window\": {\n \"title\": \"Sample Widget\",\n \"name\": \"sample_widget\",\n \"width\": 600,\n \"height\": 400\n },\n \"image\": { \n \"src\": \"images/test.png\",\n \"name\": \"sample_test\",\n \"hOffset\": 150,\n \"vOffset\": 150,\n \"alignment\": \"center\"\n },\n \"text\": {\n \"data\": \"Click Here\",\n \"size\": 36,\n \"style\": \"bold\",\n \"name\": \"sample_click\",\n \"alignment\": \"center\"\n }\n}} ";
byte[] out = data.getBytes(StandardCharsets.UTF_8);
OutputStream stream = http.getOutputStream();
stream.write(out);
System.out.println(http.getResponseCode() + " " + http.getResponseMessage());
http.disconnect();
注意: Content-Length 將自動添加。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.