我正在尝试从 API 获取数据。我需要在没有标题的邮递员中传递来自正文的值:不显示应用程序/JSON 数据。
final response = await http.post(
      "http://192.168.10.25:8080/Login/validateusername",
    body: {"username": "user@PYA"},
      headers: {'Content-Type': 'application/json'},
    );
错误信息:
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".
添加内容类型  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;
}
使用内容类型“application/json”时,只需将主体编码为 json 对象
http.Response response = await http.post( uri , headers: headers, body: JsonEncoder().convert(body));
另一种简单的方法如下
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,
);
| 归档时间: | 
 | 
| 查看次数: | 17017 次 | 
| 最近记录: |