【问题标题】:How to read Http response from flutter?如何从颤动中读取 Http 响应?
【发布时间】:2020-02-26 08:11:54
【问题描述】:

我正在尝试从 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));
}

【问题讨论】:

    标签: http flutter response


    【解决方案1】:

    您可以按如下方式实现此功能

    1.安装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 
       }
      

    【讨论】:

    • 我猜这里有问题:final response = await client .post( uri, body: bodyBytes, headers: headers, ) .timeout(Duration(seconds: 120)); }
    • 你能告诉我你想发送什么类型的数据到服务器吗?
    • {name:"bla bla",surname:"bla bla"} 这样
    • 我已经有了这 4 个步骤,但还是一样。感谢您的帮助。
    • final http.Client client,这里你没有初始化client,第2步
    猜你喜欢
    • 2021-11-08
    • 2022-07-27
    • 2016-10-26
    • 2018-12-05
    • 1970-01-01
    • 1970-01-01
    • 2016-06-03
    • 1970-01-01
    • 2017-12-18
    相关资源
    最近更新 更多