Alamofire请求参数编码

2022-05-04  本文已影响0人  冷武橘

一、URLEncodedFormParameterEncoder

参数拼接到url后面或者放在body里

HTTP body: "qux[]=x&qux[]=y&qux[]=z&baz[]=a&baz[]=b&foo[]=bar”

queryString: https://httpbin.org/get?foo=bar

URLEncodedFormParameterEncoder.default和destination: .methodDependent是等效的

1、下面三种请求例子在get请求中是完全等价的

let parameters = ["foo": "bar"]
AF.request("https://httpbin.org/get", parameters: parameters) 
AF.request("https://httpbin.org/get", parameters: parameters, encoder: URLEncodedFormParameterEncoder.default)
AF.request("https://httpbin.org/get", parameters: parameters, encoder: URLEncodedFormParameterEncoder(destination: .methodDependent))

2、拼接到url后面

AF.request("https://httpbin.org/get", method: .get, parameters: self.parmeters, encoder:URLEncodedFormParameterEncoder(destination: .queryString))

3、拼接到body后面

AF.request("https://httpbin.org", method: .post, parameters: self.parmeters, encoder:URLEncodedFormParameterEncoder(destination: .httpBody))

4、同样下面三种请求例子在post请求中是完全等价的

AF.request("https://httpbin.org/post", method: .post, parameters: parameters)
AF.request("https://httpbin.org/post", method: .post, parameters: parameters, encoder: URLEncodedFormParameterEncoder.default)
AF.request("https://httpbin.org/post", method: .post, parameters: parameters, encoder: URLEncodedFormParameterEncoder(destination: .httpBody))

二、JSONParameterEncoder

将参数json的格式编码到httpbody里面(这里大多数是指post请求,get请求没有httpbody

HTTP body: {"baz":["a","b"],"foo":["bar"],"qux":["x","y","z”]}

AF.request("https://httpbin.org/post", method: .post, parameters: parameters, encoder: JSONParameterEncoder.default)
AF.request("https://httpbin.org/post", method: .post, parameters: parameters, encoder: JSONParameterEncoder.prettyPrinted)
AF.request("https://httpbin.org/post", method: .post, parameters: parameters, encoder: JSONParameterEncoder.sortedKeys)

上一篇下一篇

猜你喜欢

热点阅读