Flutter:Http 发布请求错误无效的媒体类型:预期

标签 flutter dart dart-pub dart-http

我正在使用 http 依赖项发出 http post 请求。我在回复中遇到以下错误。我在下面发布我的代码:

flutter: Error on line 1, column 32: Invalid media type: expected /[^()<>@,;:"\\\/[\]?={} \t\x00-\x1F\x7F]+/.
      ╷
    1 │ application/json;charset=utf-8;
      │

                            ^

下面是我遇到错误的代码:

try {
    String url = 'https://app.restroapp.com/';
    Map<String, String> headers = {"Content-type": "application/json"};
    String json = '{"device_id": "abaf785580c22722", "user_id": "", "device_token": "","platform":"android"}';

    // make POST request
    Response response = await post(Uri.encodeFull(url), headers: headers, body: json);
    // check the status code for the result
    int statusCode = response.statusCode;
    // this API passes back the id of the new item added to the body
    String body = response.body;

    print(statusCode);
    print(body);

  } catch (e) {
    print(e);
  }

在postman中运行,请看下图: enter image description here

最佳答案

将其用于发布请求

 Future<Map<String, dynamic>> postRequest(String url, Map jsonMap) async{
     print('$url , $jsonMap');
     HttpClient httpClient = new HttpClient();
     HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));
     request.headers.set('content-type', 'application/json');
     request.add(utf8.encode(json.encode(jsonMap)));
     HttpClientResponse response = await request.close();
     String reply = await response.transform(utf8.decoder).join();
     print(reply);
     httpClient.close();
     Map<String, dynamic>map = json.decode(reply);
     return map;
}

关于Flutter:Http 发布请求错误无效的媒体类型:预期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57369129/

相关文章:

flutter - MaterialApp 构建器错误 : No Overlay widget found

flutter - 导航到其他屏幕时路由抛出异常 "There are multiple heroes that share the same tag within a subtree"

dart - 使用 `pub run`命令运行脚本时如何找到包目录的路径

android-studio - 我如何格式化(粗体)文本中的单词?

Flutter - 如何在页面上动态显示或隐藏应用栏

json - 在 jaguar_serializer 中运行 'serializer build' 时出错

google-chrome - 在浏览器中打开 Dart 项目时源映射不起作用

dart - 文件夹在 dart 项目中有什么相关性?

android-studio - 如何在 Android Studio 中打开现有的 Flutter 项目

firebase - 将依赖项添加到VScode中的gradle后无法同步