如何添加Alamofire URL参数

如何添加Alamofire URL参数

问题描述:

我有一个使用邮递员传递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中创建此网址?
http:// localhost:8080 /?test = 123

How would you create this url in Alamofire? http://localhost:8080/?test=123

    _url = "http://localhost:8080/"
    let parameters: Parameters = [
        "test": "123"
        ]

    Alamofire.request(_url,
                      method: .post,
                      parameters: parameters,
                      encoding: URLEncoding.default,
                      headers: headers


问题是使用 URLEncoding.default 。Alamofire根据HTTP 方法对 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

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 $ c $中使用查询字符串,它作为HTTP请求的主体发送。 c>请求,您需要将 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如何处理请求参数的更多详细信息。

您的代码应如下所示:

   _url = "http://localhost:8080/"
    let parameters: Parameters = [
        "test": "123"
        ]

    Alamofire.request(_url,
                      method: .post,
                      parameters: parameters,
                      encoding: URLEncoding(destination: .queryString),
                      headers: headers)