本文介绍了如何添加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中创建此网址?

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 请求,您需要将 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).

您可以在。

您的代码应如下所示:

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

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

这篇关于如何添加Alamofire URL参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 01:04