【问题标题】:How to calculate Content-Length of a request body of a Http Post Request如何计算 Http Post 请求的请求正文的 Content-Length
【发布时间】:2021-11-28 15:41:32
【问题描述】:

我正在尝试计算 http post 请求的请求正文的 Content-Length,但我不断收到错误,指示 Content-Length 错误。请求正文如下所示:

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

我尝试了几种解决方案,例如将正文的内容连接成一个字符串,例如以下,然后将其转换为字节数组并发送它的长度,但它不起作用。

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);

post 请求正文是 x-www-form-urlencoded 格式,内容长度必须正确计算。任何帮助表示赞赏,谢谢。

【问题讨论】:

  • 为什么需要手动计算?通常这是由底层使用的 http 库完成的。
  • 您可以尝试其中一种解决方案:stackoverflow.com/questions/50089550/…
  • 谢谢,我试试
  • 你知道任何可以计算它的库吗?谢谢

标签: java flutter http post httprequest


【解决方案1】:

您不需要制作整数列表...

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

此示例使用来自 HttpServlet 的 HttpServletResponse 对象。不确定这是否是您需要的。

我已经用了很多,效果很好。

【讨论】:

    【解决方案2】:

    我自己封装了它。一般来说,我不需要计算它。除非是特殊场合。 推荐okhttp3

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center。
    猜你喜欢
    • 2010-09-07
    • 2020-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多