Alamofire 是一个HTTP网络请求库,为开发者提供强大的HTTP的操控能力,本篇探究Alamofire 发起请求的逻辑.
使用Alamofire 发起请求:
SessionManager.default.request(urlStr, method: .post, parameters: ["aaa":"bbb"])
.response { (response) in
debugPrint(response)
}
可以看到,使用Alamofire发起请求十分的简洁优雅,只要参数以json的形势传递即可.
请求参数如何封装到 HTTP 请求报文中
相关方法:
//方法1:
open func request(
_ url: URLConvertible,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil)
-> DataRequest
{
var originalRequest: URLRequest?
do {
originalRequest = try URLRequest(url: url, method: method, headers: headers)
let encodedURLRequest = try encoding.encode(originalRequest!, with: parameters)
return request(encodedURLRequest)
} catch {
return request(originalRequest, failedWith: error)
}
}
//方法2:
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var urlRequest = try urlRequest.asURLRequest()
guard let parameters = parameters else { return urlRequest }
if let method = HTTPMethod(rawValue: urlRequest.httpMethod ?? "GET"), encodesParametersInURL(with: method) {
guard let url = urlRequest.url else {
throw AFError.parameterEncodingFailed(reason: .missingURL)
}
if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty {
let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters)
urlComponents.percentEncodedQuery = percentEncodedQuery
urlRequest.url = urlComponents.url
}
} else {
if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
}
urlRequest.httpBody = query(parameters).data(using: .utf8, allowLossyConversion: false)
}
return urlRequest
}
//方法3:
private func query(_ parameters: [String: Any]) -> String {
var components: [(String, String)] = []
for key in parameters.keys.sorted(by: <) {
let value = parameters[key]!
components += queryComponents(fromKey: key, value: value)
}
return components.map { "\($0)=\($1)" }.joined(separator: "&")
}
//方法4:
private func encodesParametersInURL(with method: HTTPMethod) -> Bool {
switch destination {
case .queryString:
return true
case .httpBody:
return false
default:
break
}
switch method {
case .get, .head, .delete:
return true
default:
return false
}
}
1.方法1逻辑: 创建URLRequest --> 对参数进行编码--> 调用 request(encodedURLRequest)
2.方法2负责对参数进行编码(在URLEncoding类中)
2.1首先检查HTTP 的方法类型,如果是GET,HEAD,DELETE 方法,就把参数
序列化后的形势,拼接到url 后面.并且对参数进行 urlencode.
2.2否则 ,先设置HTTP 头信息的 Content-Type 段,然后将参数格式化后的
形势放到URLRequest的 httpBody 中.
3.方法3 对传进来的 json 形势的 paramters 进行 HTTP 参数格式化,并且支持参数的嵌套,递归的方式解析.
请求如何发起
//方法5:
@discardableResult
open func request(_ urlRequest: URLRequestConvertible) -> DataRequest {
var originalRequest: URLRequest?
do {
/*调用传递进来的 URLRequestConvertible 对象的 asURLRequest 方法
得到 URLRequest 对象*/
originalRequest = try urlRequest.asURLRequest()
/*使用URLRequest对象创建 DataTask */
let originalTask = DataRequest.Requestable(urlRequest: originalRequest!)
let task = try originalTask.task(session: session, adapter: adapter, queue: queue)
/*创建了DataRequest*/
let request = DataRequest(session: session, requestTask: .data(originalTask, task))
/*将 DataTask 与 DataRequest做了关联*/
delegate[task] = request
/*
检查并 startRequestsImmediately (是否立即请求标识)
调用request.resume()
在这个方法中会调用task.resume,开始请求
*/
if startRequestsImmediately { request.resume() }
/*返回给外界*/
return request
} catch {
return request(originalRequest, failedWith: error)
}
}
//方法6: DataRequest
open func resume() {
guard let task = task else { delegate.queue.isSuspended = false ; return }
if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() }
task.resume()
NotificationCenter.default.post(
name: Notification.Name.Task.DidResume,
object: self,
userInfo: [Notification.Key.Task: task]
)
}
1.方法5在方法1中被调用,此时参数已经格式化完毕,包含在encodedURLRequest(URLRequest)中.
2.使用DataRequest对象,创建DataTask.
3.调用DataRequest.resume()方法,继而调用 DataTask的 resume方法,此时请求开始发送.
Alamofire HTTP请求可以总结为三个步骤, 创建URLRequest --> 参数格式化-->创建Task并resume. 这三个步骤,其实和在写原生网络请求是一样的.但是在这中间,ALamofire的还创建了一些其他对象,如DataRequest, URLEncoding等,这两个对象各司其职有着十分重要的作用,有待继续探索~.
网友评论