How to add Alamofire URL parameters

前端 未结 2 748
情深已故
情深已故 2020-12-05 02:36

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.

How would you create this url in

2条回答
  •  有刺的猬
    2020-12-05 02:40

    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)
    

提交回复
热议问题