【问题标题】:How to make HTTP POST request with url encoded header and body in Flutter/Dart如何在 Flutter/Dart 中使用 url 编码的标头和正文发出 HTTP POST 请求
【发布时间】:2022-01-05 07:48:57
【问题描述】:

我一直在尝试向需要对请求标头和正文进行编码的端点发出发布请求,但是到目前为止,我得到的响应是 400 错误。到目前为止,我获得工作请求的唯一方法是在 VSCode 中使用 curl 请求和 Thunder 客户端。以下是我的请求正文。任何形式的帮助将不胜感激。

使用flutter http包:

Response response = await post(
      Uri.parse(URL), 
      headers: {
      'Authorization': 'Basic ${base64Encode(utf8.encode('$ID:$SECRET'))}',
      'Content-Type': 'application/x-www-form-urlencoded',
      }, 
      encoding: Encoding.getByName('utf-8'),
      body: {
      'grant_type': 'refresh_token',
      'refresh_token': refreshToken,
      'redirect_uri':
          redirectUri,
      }
    );

错误:

使用 Flutter Dio 包:

Dio.Dio dio = Dio.Dio();
    Dio.Response response = await dio.post(
        URL,
        data: {
          'grant_type': 'refresh_token',
          'refresh_token': refreshToken,
          'redirect_uri':
              redirectUri,
        },
        options:
            Dio.Options(contentType: Dio.Headers.formUrlEncodedContentType, headers: <String, String>{'Authorization': 'Basic ${base64Encode(utf8.encode('$ID:$SECRET'))}'}));

错误:

【问题讨论】:

  • 您是否尝试过简单地提供 body: 'grant_type=refresh_token&amp;refresh_token=$refreshToken&amp;redirect_uri=$redirectUri' ? Afaik 这就是 x-www-form-urlencoded 所期望的
  • 仍然收到相同的 400 错误消息

标签: flutter api http dart post


【解决方案1】:

当您从服务器 400 得到响应时,api 正在访问服务器。尝试从后端调试以详细了解确切的问题。

【讨论】:

    猜你喜欢
    • 2021-01-26
    • 1970-01-01
    • 1970-01-01
    • 2022-10-18
    • 2018-07-19
    • 2023-03-04
    • 2018-09-22
    • 2015-02-18
    • 2020-01-09
    相关资源
    最近更新 更多