Alamofire4.x开源代码分析(二)请求参数和编码
2017-06-28 00:00
429 查看
请求方法
框架提供了9种方法case options = "OPTIONS" case get = "GET" case head = "HEAD" case post = "POST" case put = "PUT" case patch = "PATCH" case delete = "DELETE" case trace = "TRACE" case connect = "CONNECT" 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请求
// 以下三个写法等价 Alamofire.request("https://httpbin.org/get", parameters: parameters) // encoding defaults to `URLEncoding.default` Alamofire.request("https://httpbin.org/get", parameters: parameters, encoding: URLEncoding.default) Alamofire.request("https://httpbin.org/get", parameters: parameters, encoding: URLEncoding(destination: .methodDependent)) // https://httpbin.org/get?foo=bar
POST请求
"foo": "bar", "baz": ["a", 1], "qux": [ "x": 1, "y": 2, "z": 3 ] ] // 以下三个写法等价 Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters) Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: URLEncoding.default) Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: URLEncoding.httpBody) // HTTP body: foo=bar&baz[]=a&baz[]=1&qux[x]=1&qux[y]=2&qux[z]=3
JSON编码
以前我们需要把NSDictionary转为NSData然后用NSJSONSerialization转成JSON stringJSON编码给简化了我们操作,它会创建一个JSON作为参数放在HTTP body中,对应的Content-Type 为application/json
例子
let parameters: Parameters = [ "foo": [1,2,3], "bar": [ "baz": "qux" ] ] // Both calls are equivalent Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: JSONEncoding.default) Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: JSONEncoding(options: [])) // 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 的例子struct JSONStringArrayEncoding: ParameterEncoding { private let array: [String] init(array: [String]) { self.array = array } func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { var urlRequest = try urlRequest.asURLRequest() let data = try JSONSerialization.data(withJSONObject: array, options: []) if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") } urlRequest.httpBody = data return urlRequest } }
也可手动对请求进行编码
let url = URL(string: "https://httpbin.org/get")! var urlRequest = URLRequest(url: url) let parameters: Parameters = ["foo": "bar"] let encodedURLRequest = try URLEncoding.queryString.encode(urlRequest, with: parameters)
HTTP Headers
设置会直接改吧全局请求,可以满足请求头不断改吧的需求let headers: HTTPHeaders = [ "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", "Accept": "application/json" ] Alamofire.request("https://httpbin.org/headers", headers: headers).responseJSON { response in debugPrint(response) }
在SessionManager中提供了所有请求的默认的请求头设置,Session Manager Configurations章节中细说
下面列举一些默认的参数
Accept-Encoding:gzip;q=1.0, compress;q=0.5 Accept-Language:en;q=1.0 User-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开源代码分析(三)更新中
相关文章推荐
- struts2.X心得7--接收请求参数和struts类型转换介绍以及案例分析
- Http Url Get请求方式需要对中文参数进行编码
- 图片上传通过Bitmap转换成Base64编码然后当做请求参数上传
- 816x部分编码参数分析
- 支付:分析支付中的请求参数
- 根据指定的编码格式返回请求的参数集合
- display:table请求参数部分编码
- 封装Ajax请求,callback函数参数分析
- 前后端分离。前端POST请求参数过长,导致400错误解决办法及分析
- 对于携带请求参数的HttpGet与的HttpPost两种请求方式,代码段分析
- struts2.X心得7--接收请求参数和struts类型转换介绍以及案例分析
- Tomcat之——接收UTF-8编码GET参数请求配置
- [Servlet]HttpServletRequest的请求参数、标头、编码
- Request对象中请求参数中文编码问题
- 利用HttpClient的POST方式发起带参数的请求时,点击注册按钮无反应状态分析
- 黑马day04 表单请求参数&中文乱码分析
- 深入分析JavaWeb Item45 -- Struts2封装请求参数与类型转换
- tomcat的acess_log打印post请求参数,分析日志
- Android使用HttpUrlConnection get请求带中文参数的编码问题
- Fiddler模拟post和get请求,分析请求的参数、请求的数据