Java 如何在ApacheHttpComponents中向HttpPost添加内容长度头?
我有一个服务器,它期望内容长度作为文章标题的一部分。为了发帖,我正在使用ApacheHttpComponents库 这是预期请求的精简版本(当然包含所有必需的标题): 我使用了HttpPost的setEntity方法将StringEntity(转换的json->String->StringEntity)设置为帖子的内容。但是当我执行请求时,我最终得到了一个POST请求,它没有在它的头中指定内容长度 是否仍要添加此缺少的标题 (我尝试了setHeader()来设置内容长度,这抛出了一个错误,表示内容长度已经存在) 这是我用来创建POST请求的代码:Java 如何在ApacheHttpComponents中向HttpPost添加内容长度头?,java,http-post,apache-httpcomponents,content-length,Java,Http Post,Apache Httpcomponents,Content Length,我有一个服务器,它期望内容长度作为文章标题的一部分。为了发帖,我正在使用ApacheHttpComponents库 这是预期请求的精简版本(当然包含所有必需的标题): 我使用了HttpPost的setEntity方法将StringEntity(转换的json->String->StringEntity)设置为帖子的内容。但是当我执行请求时,我最终得到了一个POST请求,它没有在它的头中指定内容长度 是否仍要添加此缺少的标题 (我尝试了setHeader()来设置内容长度,这抛出了一个错误,表示内
//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);
尝试:
这会将内容长度设置为0。HttpClient会根据所附消息实体的属性和实际协议设置自动生成
内容长度
和传输编码
头值
不要手动设置这些标题 您可以添加用于创建请求的代码吗?当然可以。。将使用我的代码更新帖子您如何确定未发送
内容长度
标题?
//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);
httppost.setHeader(HTTP.CONTENT_LEN,"0");