【问题标题】:How to add a body to GET request in dart/flutter?如何在 dart/flutter 中向 GET 请求添加正文?
【发布时间】:2020-05-15 17:07:24
【问题描述】:

我正在尝试从需要带有 GET 请求的正文的 API 获得响应。它适用于 POSTMAN,因为它允许我们将正文添加到 GET 请求。但是如何使用 dart 添加 GET 请求呢?

【问题讨论】:

  • 尝试使用低级Request
  • 有什么使用方法的例子吗?
  • 创建Request,添加你的body,最后调用send()方法?

标签: android ios http flutter dart


【解决方案1】:

首先你需要在 pubspec.yaml 中添加这个依赖

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  http: ^0.11.3+16

下面是flutter中调用API的代码sn-ps。

const baseUrl = "https://jsonplaceholder.typicode.com";

class NetworkApi {
  static Future getUsers() {
    var url = baseUrl + "/users";
    return http.get(url);
  }

  static Future getImages(){
    return http.post('http://xyz.in/api.php',body: {
      "parameter" : "value"
    });
  }
}

下面是从 dart 类调用 API。

getImages(){
    NetworkApi.getImages().then((response){
      setState(() {
          print("Response Status");
          print("Response : " + response.body);
          var data = json.decode(response.body);
          var imagesData = data["data"] as List;
//          images = list.map((model) => Data.fromJson(model)).toList();
        images = imagesData.map<Data>((json) => Data.fromJson(json)).toList();
          print("Images : " + images.length.toString());
      });
    });
  }

【讨论】:

  • 可以将正文添加到 POST 请求,但我想将正文添加到 GET 请求。
  • 这是你的正文 return http.post('xyz.in/api.php',body: { "parameter" : "value" });
【解决方案2】:

如果通过正文表示您正在尝试附加查询参数,那么您可以尝试以下操作:

var body = {
  'param1': 'one',
  'param2': 'two',
};
var uri =
    Uri.https('www.test.com', '/api/test', body);
var response = await http.get(uri, headers: {
  HttpHeaders.authorizationHeader: 'Token $token',
  HttpHeaders.contentTypeHeader: 'application/json',
});

查看这里了解更多信息:https://api.dart.dev/stable/2.0.0/dart-core/Uri/Uri.https.html

【讨论】:

    猜你喜欢
    • 2021-02-25
    • 1970-01-01
    • 1970-01-01
    • 2020-10-10
    • 2019-07-16
    • 2011-07-03
    • 1970-01-01
    • 2018-08-04
    • 1970-01-01
    相关资源
    最近更新 更多