【发布时间】:2013-04-10 12:35:47
【问题描述】:
我有一个服务器,它期望 Content-Length 作为 POST 标头的一部分。对于 POST,我使用的是 Apache HttpComponents 库。
这是预期请求的精简版本(当然包含所有必需的标头):
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 请求,它没有在其标头中指定 Content-length。
还有没有添加这个缺失的标题?
(我尝试 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);
【问题讨论】:
-
您可以添加用于创建请求的代码吗?
-
当然..会用我的代码更新帖子
-
您如何确定
Content-Length标头没有被发送?
标签: java http-post apache-httpcomponents content-length