如何将查询参数添加到Dart http请求? [英] How do you add query parameters to a Dart http request?
问题描述
如何正确将查询参数添加到Dart http获取请求?尝试将‘?param1 = one& param2 = two’添加到我的网址时,我无法获得正确响应的请求,但是在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¶m2=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¶m2=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变量。
The ${widget.pk} is simply a integer value being pass (See the value 123 in the workingStringInPostman variable.
在需要使用Uri参数的情况下,qParams可以方便使用。
The qParams is there for connivence, in case a Uri parameter is needed.
A代码
推荐答案
您将要构造一个 Uri
You'll want to construct a Uri
and use that for the request. Something like
var queryParameters = {
'param1': 'one',
'param2': 'two',
};
var uri =
Uri.https('www.myurl.com', '/api/v1/test/${widget.pk}', queryParameters);
var 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屋!