请求方法
框架提供了9种方法
1case options = "OPTIONS" 2 case get = "GET" 3 case head = "HEAD" 4 case post = "POST" 5 case put = "PUT" 6 case patch = "PATCH" 7 case delete = "DELETE" 8 case trace = "TRACE" 9 case connect = "CONNECT" 10 Alamofire.request("https://httpbin.org/post", method: .post)
如果不指定默认使用GET方法
参数编码
Alamofire提供了三种类型的参数编码:URL, JSON 和 PropertyList.也可以遵守ParameterEncoding协议来自定义.
<!--more-->URL编码
- .methodDependent//默认方法 根据请求方法判断(GET直接拼接到URL中,HEAD and DELETE放到HTTP body中)
- .queryString//直接拼接到URL中
- .httpBody//放到HTTP body中
GET请求
1// 以下三个写法等价 2Alamofire.request("https://httpbin.org/get", parameters: parameters) // encoding defaults to `URLEncoding.default` 3Alamofire.request("https://httpbin.org/get", parameters: parameters, encoding: URLEncoding.default) 4Alamofire.request("https://httpbin.org/get", parameters: parameters, encoding: URLEncoding(destination: .methodDependent)) 5 6// https://httpbin.org/get?foo=bar
POST请求
1 "foo": "bar", 2 "baz": ["a", 1], 3 "qux": [ 4 "x": 1, 5 "y": 2, 6 "z": 3 7 ] 8] 9 10// 以下三个写法等价 11Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters) 12Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: URLEncoding.default) 13Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: URLEncoding.httpBody) 14 15// HTTP body: foo=bar&baz[]=a&baz[]=1&qux[x]=1&qux[y]=2&qux[z]=3 16
JSON编码
以前我们需要把NSDictionary转为NSData然后用NSJSONSerialization转成JSON string JSON编码给简化了我们操作,它会创建一个JSON作为参数放在HTTP body中,对应的Content-Type 为application/json
例子
1let parameters: Parameters = [ 2 "foo": [1,2,3], 3 "bar": [ 4 "baz": "qux" 5 ] 6] 7// Both calls are equivalent 8Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: JSONEncoding.default) 9Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: JSONEncoding(options: [])) 10 11// HTTP body: {"foo": [1, 2, 3], "bar": {"baz": "qux"}}
Property List 编码
Property List编码会创建一个plist作为参数放在HTTP body中,对应的Content-Type 为application/x-plist
自定义 Encoding
如果框架提供的参数编码方式不能满足需求,可以自定义编码方式,下面是一个自定义JSONStringArrayEncoding转JSON string array 的例子
1struct JSONStringArrayEncoding: ParameterEncoding { 2 private let array: [String] 3 4 init(array: [String]) { 5 self.array = array 6 } 7 8 func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { 9 var urlRequest = try urlRequest.asURLRequest() 10 11 let data = try JSONSerialization.data(withJSONObject: array, options: []) 12 13 if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { 14 urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") 15 } 16 17 urlRequest.httpBody = data 18 19 return urlRequest 20 } 21}
也可手动对请求进行编码
1let url = URL(string: "https://httpbin.org/get")! 2var urlRequest = URLRequest(url: url) 3 4let parameters: Parameters = ["foo": "bar"] 5let encodedURLRequest = try URLEncoding.queryString.encode(urlRequest, with: parameters)
HTTP Headers
设置会直接改吧全局请求,可以满足请求头不断改吧的需求
1let headers: HTTPHeaders = [ 2 "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", 3 "Accept": "application/json" 4] 5 6Alamofire.request("https://httpbin.org/headers", headers: headers).responseJSON { response in 7 debugPrint(response) 8}
在SessionManager中提供了所有请求的默认的请求头设置,Session Manager Configurations章节中细说 下面列举一些默认的参数
1Accept-Encoding:gzip;q=1.0, compress;q=0.5 2Accept-Language:en;q=1.0 3User-Agent:iOS Example/1.0 (com.alamofire.iOS-Example; build:1; iOS 10.0.0) Alamofire/4.0.0
Authentication验证
Authentication验证基于系统 URLCredential and URLAuthenticationChallenge框架,授权验证通常需要与后台服务器沟通来形成. 支持一下验证方案
-
HTTP Basic
-
HTTP Digest
-
Kerberos
-
NTLM 例子
let user = "user" let password = "password"
Alamofire.request("https://httpbin.org/basic-auth/\(user)/\(password)") .authenticate(user: user, password: password) .responseJSON { response in debugPrint(response) }
let user = "user" let password = "password"
var headers: HTTPHeaders = [:]
if let authorizationHeader = Request.authorizationHeader(user: user, password: password) { headers[authorizationHeader.key] = authorizationHeader.value }
Alamofire.request("https://httpbin.org/basic-auth/user/password", headers: headers) .responseJSON { response in debugPrint(response) }
let user = "user" let password = "password"
let credential = URLCredential(user: user, password: password, persistence: .forSession)
Alamofire.request("https://httpbin.org/basic-auth/\(user)/\(password)") .authenticate(usingCredential: credential) .responseJSON { response in debugPrint(response) }
系列目录
- Alamofire4.x开源代码分析(一)使用方法
- Alamofire4.x开源代码分析(二)请求参数和编码
- Alamofire4.x开源代码分析(三)更新中