如何向 Dart http 请求添加查询参数? [英] How do you add query parameters to a Dart http request?

查看:41
本文介绍了如何向 Dart http 请求添加查询参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何正确地向 Dart http get 请求添加查询参数?尝试将?param1=one&param2=two"附加到我的 url 时,我无法让我的请求正确响应,但它在 Postman 中可以正常工作.这是我的代码的要点:

How do you correctly add query parameters to a Dart http get request? I been unable to get my request to respond correctly when trying to append the '?param1=one&param2=two' to my url, yet it works correctly in Postman. Here's the gist of my code:

    final String url = "https://www.myurl.com/api/v1/test/";
    String workingStringInPostman = "https://www.myurl.com/api/v1/test/123/?param1=one&param2=two";

    Map<String, String> qParams = {
     'param1': 'one',
     'param2': 'two',
    };


   var res = await http
      .get(Uri.encodeFull("$url${widget.pk}/"),
      headers: {HttpHeaders.authorizationHeader: "Token $token", 
        HttpHeaders.contentTypeHeader: "application/json"},
);

${widget.pk} 只是一个正在传递的整数值(参见workingStringInPostman 变量中的值 123.

The ${widget.pk} is simply a integer value being pass (See the value 123 in the workingStringInPostman variable.

qParams 是为了方便,以防需要 Uri 参数.

The qParams is there for connivence, in case a Uri parameter is needed.

欢迎提供代码示例.

推荐答案

您需要构造一个 Uri 并将其用于请求.类似的东西

You'll want to construct a Uri and use that for the request. Something like

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

参见 https://api.dartlang.org/stable/2.0.0/dart-core/Uri/Uri.https.html

这篇关于如何向 Dart http 请求添加查询参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆