【问题标题】:How can I implement Post API call using Dart http library, flutter [closed]如何使用 Dart http 库实现 Post API 调用,flutter [关闭]
【发布时间】:2018-08-12 16:55:26
【问题描述】:

我试图在颤振中使用 http Dart 库执行POST 请求。但我无法找到指定请求正文的方法。有人可以举个例子吗?非常感谢

【问题讨论】:

    标签: api http post dart flutter


    【解决方案1】:

    首先在你的pubspec.yamllike中指定http

    dependencies:
      flutter:
        sdk: flutter
    
      http: ^0.11.3+16
    

    然后只需导入并使用它。 最小的示例如下所示:

    import 'dart:async';
    import 'dart:convert';
    import 'package:http/http.dart' as http;
    
    static Future<Map> getData() async {
      http.Response res = await http.get(url); // get api call
      Map data = JSON.decode(res.body);
      return data;
    }
    
    static Future<Map> postData(Map data) async {
      http.Response res = await http.post(url, body: data); // post api call
      Map data = JSON.decode(res.body);
      return data;
    }
    

    创建http.Client并将其用于api调用

     //To use Client and Send methods
    
     http.Client client = new http.Client(); // create a client to make api calls
    
     Future<Map> getData() async {
      http.Request request = new http.Request("GET", url);  // create get request
      http.StreamedResponse response = await client.send(request); // sends request and waits for response stream
      String responseData = await response.stream.transform(UTF8.decoder).join(); // decodes on response data using UTF8.decoder
      Map data = JSON.decode(responseData); // Parse data from JSON string
      return data;
    }
    

    希望有帮助!

    【讨论】:

    • 我想知道的是如何使用Request对象和Client.send方法来实现。
    • 我已经编辑了实现相同的答案,不,该示例适用于我的用例。根据您的用例,应用转换器和其他数据变异操作。希望对您有所帮助。
    • 如何处理http cookie,响应后读取http cookie并在请求中发送cookie?
    • @HemanthRaj 我理解的第一部分和第二部分是获取和发布。但最后一部分是 HttpClient getData 它是干什么用的?它与第一种方法有何不同?
    • 它只是另一种制作getRequest的方式,类似于您也可以发布帖子。我只是想展示另一种提出请求的方式。但是,您可以只使用最好的。
    猜你喜欢
    • 2021-01-26
    • 2021-05-14
    • 2019-07-05
    • 2018-05-23
    • 2017-11-22
    • 1970-01-01
    • 2020-12-21
    • 2021-10-25
    相关资源
    最近更新 更多