首页 > 解决方案 > 如何在颤动的http post请求中发送自定义标头

问题描述

我的颤振项目中有http包。我想发送带有自定义标头的发布请求。这是我的代码片段。它将使用 http 作为自定义标头明确我的问题。它总是运行 else 语句意味着响应类型不是 200,它给了我提供的错误令牌无效。但在邮递员身上,它工作正常

Map data = {
    'user_fullname': _name,
    'user_address': _address,
    'user_mobile': _phone,
  };
  var tokenData = {
    'User_token': token,
    'Content-Type': 'application/x-www-form-urlencoded'
  };

  final response = await http.post(url, body: data, headers: tokenData);
  if (response.statusCode == 200) {
    print(response.body);
  } else {
    print(response.body);
  }

邮递员测试

标签: httpflutterdart

解决方案


我猜你正在将无效类型传递给发布请求。(标题必须是Map<String, String>(我不确定飞镖tokenData在运行时从什么推断),正文可以是动态的,等等)

  final String url = 'YOUR_API_URL';
  final Map<String, String> tokenData = {
   "Content-type": "application/x-www-form-urlencoded",
   "user_token": token
  };
  final Map<String, String> data = { //is _phone a String?
    'user_fullname': _name,
    'user_address': _address,
    'user_mobile': _phone,
  };

  final Response response = await post(url, headers: tokenData, body: data);

  if (response.statusCode == 200) {
    print(response.body);
  } else {
    print(response.body);
  }
}

正文只能是 a String、 aList<int>或 aMap<String, String>

https://pub.dev/documentation/http/latest/http/Client/post.html所述


推荐阅读