【问题标题】:How To deal with Response after post request dart httpClient发布请求后如何处理响应 dart httpClient
【发布时间】:2020-03-24 20:49:05
【问题描述】:

所以我在发出 post 请求时遇到了 Flutter http 包的问题,​​所以我使用了 dart HttpClient。我根据某处描述的内容提出了发布请求,但在获得回复时遇到问题。这是我的代码

 Future<HttpClientResponse> submit() async {
 print('start');
  Map<String, dynamic> data = { 'title' : 'My first post' };
  String jsonString = json.encode(data); // encode map to json
  String paramName = 'param'; // give the post param a name
  String formBody = paramName + '=' + Uri.encodeQueryComponent(jsonString);
  List<int> bodyBytes = utf8.encode(formBody); // utf8 encode
  HttpClientRequest request =
      await HttpClient().postUrl(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
  // it's polite to send the body length to the server
  request.headers.set('Content-Length', bodyBytes.length.toString());
  request.headers.set('Content-Type', 'application/json');
  request.add(bodyBytes);
  print('done');
  return await (request.close());
}

我如何得到这个请求的响应?

【问题讨论】:

  • submit().then((response) {...})
  • @pskink 提交方法进入哪里?
  • 你想什么时候使用它?在某个按钮的点击监听器上?
  • @pskink 我在颤振应用程序中使用它。我有一个按钮调用提交方法
  • 所以我不明白你之前的问题:"where does the submit method go into" 如果你已经在监听器中调用了submit() 方法

标签: flutter dart


【解决方案1】:
      HttpClientResponse response = await request.close();
      response.transform(utf8.decoder).listen((contents) {
        print(data); // <- response content is here
      });

这将返回 HttpCLientResponse,更多信息 https://api.dartlang.org/stable/2.6.1/dart-io/HttpClient-class.html

【讨论】:

  • 但是我不能像 response.body 那样调用来获取响应的值
【解决方案2】:

我从docs找到这个

new HttpClient().get('localhost', 80, '/file.txt')
     .then((HttpClientRequest request) => request.close())
     .then((HttpClientResponse response) {
       response.transform(utf8.decoder).listen((contents) {
         // handle data
       });
     });

或使用http library 我已经创建了一个可以处理所有获取请求的通用方法,

  Future<String> getRequest([var endpoints, var queryParameters]) async {
    var uri = Uri.https(NetworkUrl.BASE_URL_1, endpoints, queryParameters);
    uri.replace(queryParameters: queryParameters);
    var response =
        await http.get(Uri.encodeFull(uri.toString()));
//Retrun reponse here 
    if (response.statusCode == 200) return response.body;
  }

要从上述方法得到响应,

  Future<String> deletePostApi() async {
    await NetworkRepository()
        .getRequest(NetworkUrl.deletePost + '${widget.mFeedData.post_id}')
        .then((value) {// <=value is json respone
      var dataConvertedToJSON = json.decode(value);
      print("checkEmailResp" + dataConvertedToJSON.toString());
    });
  }

【讨论】:

  • 我不想使用flutter http包,因为我使用它时会出错。
  • 谢谢,我已经知道了,而且之前有人已经建议过了。但是谢谢你,我赞成你的回答
猜你喜欢
  • 1970-01-01
  • 2011-07-18
  • 2019-08-08
  • 1970-01-01
  • 2021-12-02
  • 2018-01-26
  • 2015-04-14
  • 2020-02-24
  • 1970-01-01
相关资源
最近更新 更多