【问题标题】:dart / flutter how to make http post request with empty body飞镖/颤振如何用空体发出http post请求
【发布时间】:2022-11-03 13:11:58
【问题描述】:

我正在尝试调用 post url,但正文有效负载需要为空。在向邮递员请求 api 时,它工作正常。但是,当从 dart http.post 调用时,它不起作用。

这是我的代码

final response = await http.post(Uri.parse("$baseUrl/api/logout"),
headers: {
  "Accept": "*/*",
},
);

这导致 400 响应代码

这是我的原始 http 请求

POST /api/logout HTTP/1.1
Host: <url>
Accept: */*

这导致 200 响应代码。

【问题讨论】:

    标签: flutter dart http


    【解决方案1】:

    改用它来做到这一点。

    尝试保持 json body null 的

    headers: {
        "Accept": "*/*",
        "Content-Length" : 0
      }
    

    【讨论】:

    • api是post api不能用get
    • 这也行不通。
    【解决方案2】:

    如果你想制作一个没有正文的HTTP Request。您需要使用HEAD 方法。

      Future httHead() async {
       var baseUrl = Uri.parse("https://stackoverflow.com/");
       final response = await http.head(baseUrl,
       headers: {
         "Accept": "*/*",
       },
    
      );
     }
    

    【讨论】:

    • 抱歉,不使用 HEAD
    【解决方案3】:

    你可以试试这样

    var request = {"": ""};
    
    _formRepository.mailWillToOwner(id, request, (response, error) async {
      if (response != null) {
        if (response.success == true) {
          showMessage(response.message, isToast: true);
        } else {
          showMessage(response.message, isToast: true);
        }
      } else {
        showMessage(error);
      }
    });
    

    如果您的请求正文是 map 或 map<dynamic,string>,它也可以工作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-28
      • 2020-12-25
      • 2020-11-05
      • 2022-07-27
      • 2019-02-05
      相关资源
      最近更新 更多