How to add Alamofire URL parameters

痞子三分冷 提交于 2019-11-28 18:43:10

The problem is that you're using URLEncoding.default. Alamofire interprets URLEncoding.default differently depending on the HTTP method you're using.

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.

In order to use a query string in a POST request, you need to change your encoding argument to URLEncoding(destination: .queryString).

You can see more details about how Alamofire handles request parameters here.

Your code should look like:

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

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

If you want your parameters to be used in querystring, use .queryString as URLEncoding, as in: (I assume you have headers somewhere)

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

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

This form is suggested by Alamofire author because it's more coincise to the other, see screenshot:

See original here

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!