我有一个使用 Postman 传入 URL 参数的工作场景.现在,当我尝试在 Swift 中通过 Alamofire 执行此操作时,它不起作用.
I have a working scenario using Postman passing in URL parameters. Now when I try to do it via Alamofire in Swift, it does not work.
您将如何在 Alamofire 中创建此网址?localhost:8080/?test=123
How would you create this url in Alamofire? localhost:8080/?test=123
_url = "localhost:8080/" let parameters: Parameters = [ "test": "123" ] Alamofire.request(_url, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: headers 推荐答案问题在于您正在使用 URLEncoding.default.Alamofire 根据您使用的 HTTP method 以不同方式解释 URLEncoding.default.
The problem is that you're using URLEncoding.default. Alamofire interprets URLEncoding.default differently depending on the HTTP method you're using.
对于 GET、HEAD 和 DELETE 请求,URLEncoding.default 将参数编码为查询字符串并将其添加到 URL,但对于任何其他方法(例如 POST),参数会被编码为查询字符串并作为 HTTP 请求的正文发送.
For GET, HEAD, and DELETE requests, URLEncoding.default encodes the parameters as a query string and adds it to the URL, but for any other method (such as POST) the parameters get encoded as a query string and sent as the body of the HTTP request.
为了在 POST 请求中使用查询字符串,您需要将 encoding 参数更改为 URLEncoding(destination: .queryString).
In order to use a query string in a POST request, you need to change your encoding argument to URLEncoding(destination: .queryString).
您可以在此处查看有关 Alamofire 如何处理请求参数的更多详细信息.
You can see more details about how Alamofire handles request parameters here.
您的代码应如下所示:
_url = "localhost:8080/" let parameters: Parameters = [ "test": "123" ] Alamofire.request(_url, method: .post, parameters: parameters, encoding: URLEncoding(destination: .queryString), headers: headers)更多推荐
如何添加 Alamofire URL 参数
发布评论