How to read Http response from flutter?

六月ゝ 毕业季﹏ 提交于 2021-01-29 14:44:58

问题


I'm trying to read reponse from HTTP in flutter but I didnt read. I posted the request. Can anyone know, what is wrong ?

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:


You can achieve this functionality as follow

1.install http package and import it as follow

    import 'package:http/http.dart' as http;
  1. Create an instance of http or http.Client as you did

    final http.Client _client = http.Client();
    
  2. Send the request to server as follow

    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. Then you can read the response as

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


来源:https://stackoverflow.com/questions/60409417/how-to-read-http-response-from-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!