如何添加 Alamofire URL 参数 [英] How to add Alamofire URL parameters

查看:28
本文介绍了如何添加 Alamofire URL 参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 Postman 传入 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 method 以不同方式解释 URLEncoding.default.

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

对于 GETHEADDELETE 请求,URLEncoding.default 将参数编码为查询字符串并将其添加到 URL,但对于任何其他方法(例如 POST),参数会被编码为查询字符串并作为 HTTP 请求的正文发送.

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).

您可以在此处查看有关 Alamofire 如何处理请求参数的更多详细信息.

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

您的代码应如下所示:

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

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆