如何从 flutter 中读取 Http 响应?

How to read Http response from flutter?

我试图在 flutter 中读取来自 HTTP 的响应,但我没有读取。 我发布了请求。谁能知道,怎么了?

final http.Client client;

Future<http.Response> post(
  Uri uri, {
    Map<String, dynamic> postParams,
    String accessToken,
  }) async {
log.info(uri.toString());
log.info('postParams: ${postParams?.toString()}');

///Encode map to bytes
String jsonString = json.encode(postParams);
List<int> bodyBytes = utf8.encode(jsonString);

Map headers = {
  HttpHeaders.contentTypeHeader: 'application/json; charset=utf-8',
};


final response = await client
    .post(
  uri,
  body: bodyBytes,
  headers: headers,
)
    .timeout(Duration(seconds: 120));
}

您可以通过以下方式实现此功能

1.install http 打包导入如下

    import 'package:http/http.dart' as http;
  1. 像您一样创建 httphttp.Client 的实例

    final http.Client _client = http.Client();
    
  2. 如下向服务器发送请求

    var url = 'https://example.com/store/.....'; 
    
    final Map<String, dynamic> data= {"name":"John Doe", "email":"johndoe@email.com"};
    
    final Map<String, String> _headers = {
        "Content-Type": "application/json",
        "Accept": "application/json",
     };
    
    var response = await _client.post(url, body:data, headers:_headers);
    
  3. 然后您可以阅读响应

     if(response.statusCode == 200) {
       var decoded = json.decode(response.body);
       print(decoded);
    
       // The Rest of code 
     }