Alamofire4.x开源代码分析(二)请求参数和编码

本文详细介绍了Alamofire框架中的请求方法、参数编码方式(包括URL、JSON及PropertyList编码),并提供了如何自定义编码的具体实例。此外还讲解了HTTP头部设置及认证验证的方法。

请求方法

框架提供了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 string JSON编码给简化了我们操作,它会创建一个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)
    }

系列目录

转载于:https://my.oschina.net/roycehe/blog/1057850

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值