简体   繁体   English

如何计算 Http Post 请求的请求正文的 Content-Length

[英]How to calculate Content-Length of a request body of a Http Post Request

I am trying to calculate the Content-Length of the request body of a http post request but I keep getting error that indicated wrong Content-Length.我正在尝试计算 http 发布请求的请求正文的内容长度,但我不断收到指示错误内容长度的错误。 Request body looks like following:请求正文如下所示:

Map<String, String> body = {
  'grant_type': 'authorization_code',
  'client_id': 'clientid',
  'code': authCode,
  'redirect_uri': 'http://localhost:8080/login/callback',
  'code_verifier':
      'codeverifier',
};

I tried couple solutions like concatenating content of the body into one string such as following and then convert it into byte array and send the length of it but it didn't work.我尝试了几种解决方案,例如将正文的内容连接成一个字符串,例如以下内容,然后将其转换为字节数组并发送它的长度,但没有奏效。

String bodyStr = "grant_type:authorization_code" +
    "client_id:clientid" +
    "code:{$authCode}" +
    "redirect_uri:http://localhost:8080/login/callback" +
    "code_verifier:codeverifier";
    List<int> bytes = utf8.encode(bodyStr);

The post request body is x-www-form-urlencoded format and content length has to be calculated correctly. post 请求正文是 x-www-form-urlencoded 格式,内容长度必须正确计算。 Any help is appreciated, thanks.任何帮助表示赞赏,谢谢。

You don't need to make a list of integer...你不需要制作一个整数列表......

String bodyStr = "...";
byte[] bytes = bodyStr.getBytes(Charset.forName("UTF-8"));
int len = bytes.length;
response.setContentLength(len);
response.getOutputStream().write(bytes);

This example is using the HttpServletResponse object from a HttpServlet.此示例使用来自 HttpServlet 的 HttpServletResponse 对象。 Not sure if that's what you need.不确定这是否是您所需要的。

I have used this a fair amount, it works well.我已经大量使用了它,效果很好。

I encapsulated it myself.我自己封装的。 Generally, I don't need to calculate it.一般来说,我不需要计算它。 Unless it's a special occasion.除非是特殊场合。 Okhttp3 is recommended推荐okhttp3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM