1
我有一個服務器期望Content-Length作爲POST標題的一部分。對於POSTing,我使用的是Apache HttpComponents庫。如何將Content-Length頭添加到Apache HttpComponents中的HttpPost?
這是預期的請求的一個精簡版(具有所有所需要頭ofcourse):
POST /ParlayREST/1.0/sample/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Host: server.url.com:8080
Content-Length: 287
{
"listenerURL":"http://application.example.com/notifyURL"},
"sessionId":"12345"
}
我已經使用的HttpPost的setEntity方法來設置StringEntity(換算json - > String - > StringEntity)作爲POST的內容。但是當我執行這個請求時,我最終得到一個POST請求,它在它的頭部中沒有指定內容長度。
無論如何添加這個缺失的標題?
(我想的setHeader()設置的Content-Length這引發了錯誤說,內容長度已經存在)
這是我使用來創建POST請求的代碼:
//Convert the registration request object to json
StringEntity registrationRequest_json_entity = new StringEntity(gsonHandle.toJson(registrationRequest));
registrationRequest_json_entity.setContentType("application/json");
//Creating the HttpPost object which contains the endpoint URI
HttpPost httpPost = new HttpPost(Constants.CLIENT_REGISTRATION_URL);
httpPost.setHeader(HTTP.CONTENT_TYPE,"application/json");
httpPost.setHeader("Accept","application/json");
httpPost.setHeader(HTTP.TARGET_HOST,Constants.REGISTRATION_HOST + ":" + Constants.REGISTRATION_PORT);
//Set the content as enitity within the HttpPost object
httpPost.setEntity(registrationRequest_json_entity);
HttpResponse response = httpClient.execute(httpPost, new BasicHttpContext());
HttpEntity entity = response.getEntity();
if (entity != null) {
//work on the response
}
EntityUtils.consume(entity);
您可以添加用於創建請求的代碼嗎? – vptheron 2013-04-10 13:18:51
當然..將更新與我的代碼帖子 – user2265993 2013-04-11 06:51:25
你如何確定'Content-Length'頭沒有被髮送? – Perception 2013-04-19 05:03:04