如何添加 Alamofire URL 参数

编程入门 行业动态 更新时间:2024-10-15 02:27:49
本文介绍了如何添加 Alamofire URL 参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个使用 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 参数

本文发布于:2023-11-26 02:20:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1632262.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:参数   Alamofire   URL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!