java post 长度_java - 如何在Apache HttpComponents中将Content-Length标头添加到HttpPost? - 堆栈内存溢出...

我有一台服务器,它希望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的内容。 但是,当我执行请求时,我最终得到了一个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);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值