如何在 Flutter 上使用 Json Body 进行 Http Post

3 dart flutter

我正在尝试从 API 获取数据。我需要在没有标题的邮递员中传递来自正文的值:不显示应用程序/JSON 数据。

final response = await http.post(
      "http://192.168.10.25:8080/Login/validateusername",
    body: {"username": "user@PYA"},
      headers: {'Content-Type': 'application/json'},
    );
Run Code Online (Sandbox Code Playgroud)

错误信息:

E/flutter (28851): [ERROR:flutter/shell/common/shell.cc(184)] Dart Error: Unhandled exception:
E/flutter (28851): Bad state: Cannot set the body fields of a Request with content-type "application/json".
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

Rah*_*var 6

添加内容类型 application/json

Future<String> apiRequest(String url, Map jsonMap) async {
  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();
  // todo - you should check the response.statusCode
  String reply = await response.transform(utf8.decoder).join();
  httpClient.close();
  return reply;
}
Run Code Online (Sandbox Code Playgroud)

  • 错误:状态错误:无法设置内容类型为“application/json”的请求的正文字段。 (3认同)

Ade*_*adi 5

使用内容类型“application/json”时,只需将主体编码为 json 对象

http.Response response = await http.post( uri , headers: headers, body: JsonEncoder().convert(body));
Run Code Online (Sandbox Code Playgroud)


Dil*_*ake 5

另一种简单的方法如下

import 'package:http/http.dart' as http;

String body = json.encode({
    'foo': 'bar',
    'complex_foo' : {
        'name' : 'test'     
    }
});

http.Response response = await http.post(
    url: 'https://example.com',
    headers: {"Content-Type": "application/json"},
    body: body,
);
Run Code Online (Sandbox Code Playgroud)