Alamofire GET请求无法正常运行

时间:2018-02-02 22:46:32

标签: ios swift get request alamofire

我发出了一个GET请求。

let parameters: Parameters = [
    "filter": ["fruit": "apple"]
     ]

Alamofire.request(urlStr, method: .get, parameters: parameters, encoding:URLEncoding.default).responseJSON { response in
           print(response.request!)
     }

但是,GET请求无法正常工作。我认为参数根本不正确。这是使用以下代码print(response.request!)

打印出来的网址请求
https://api.example.com/fruits?apiKey=1&filter%5Bfruit%5D=apple

但是,使用邮递员我可以使用以下URL请求发送正确的请求并获得正确的响应。

https://api.example.com/fruits?apiKey=1&filter={"fruit":"apple"}

我不知道如何解决这个问题。我尝试了很多种编码类型,但都没有。任何提示或建议表示赞赏

编辑:我确实从服务器获得了使用alamofire的响应,但它不是正确的数据,因为这些参数被忽略。但是,我从邮递员得到的回答是正确的。

1 个答案:

答案 0 :(得分:1)

Morning Curt,

Since there is no published specification for how to encode collection types, the convention of appending [] to the key for array values (foo[]=1&foo[]=2), and appending the key surrounded by square brackets for nested dictionary values (foo[bar]=baz) [is used].

In my opinion you should really avoid passing array objects in query strings. You could change your request to something like:

apiKey=1&fruit=apple

Where does presence of field fruit itself indicates response should be filtered.

Moreover:

Instead of using GET, you should consider using POST or PUT and passing values via JSON, XML, or another well-defined format. This could require server side changes obviously.

If server side is out of your control, you should consider manually encoding these parameters instead.

Source

You can find here an example of manually encoding.

Happy coding!