首页 > 解决方案 > 如何计算 Http Post 请求的请求正文的 Content-Length

问题描述

我正在尝试计算 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);

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

标签: javaflutterhttpposthttprequest

解决方案


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


推荐阅读