强制url中的查询参数格式



我在我的flutter应用程序中有一个方法,通过将参数传递到url 来查询get请求

Future<Map<String, dynamic>> getData(
{String path, String token, Map<String, String> params}) async {
try {
Uri uri = Uri.parse(path);
Uri newUri = uri.replace(queryParameters: params); // http://some/path/?param=1...
final http.Response response =
await http.get(newUri, headers: APIHeader.authorization(token));
final jsonResponse = json.decode(response.body);
if (response.statusCode != 200) {
throw ServerException(jsonResponse["error"]);
}
return jsonResponse['result'];
} catch (error) {
throw error;
}
}

其中Uri方法生成的url为http://some/path/?param=1...

它工作得很好,但是如果我想用它只按id查询,那么查询参数格式只是id

http://some/path/1

如果我使用上面的方法并以{'id':'1'}格式发送参数,那么我会得到url

http://some/path/?id=1

有没有办法在我的后端强制参数采用../?id=1格式,或者有没有办法让Uri方法识别这些差异?

我的id后端路由器是

router.get('/some/path/:id', controller.get);

你必须自己做这项工作。

URI查询参数被放入URI的查询部分。

Uri类不知道您的服务在URI的非查询部分也接受其参数。如果你想让某个东西成为URI的路径的一部分,你必须把它放在那里。

所以,类似于:

Uri addParameters(Uri baseUri, Map<String, String> params) {
if (query.length == 1 && params.containsKey("id")) {
// ID only. Assume baseUri ends in `/`.
return baseUri.resolve(params["id"]);
}
return baseUri.replace(queryParameters: params);
}

最新更新