Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
985 views
in Technique[技术] by (71.8m points)

swift - How to add Alamofire URL parameters

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 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...