在使用 Moya 的過程中即彪,會遇到這種情況:url 當(dāng)中需要?jiǎng)討B(tài)設(shè)置參數(shù),body 中也要設(shè)置參數(shù)。
比如請求的 URL 當(dāng)中需要添加 userID
隶校,在 body 當(dāng)中需要傳入一個(gè) JSON 格式的參數(shù) {"roomID": "123"}
漏益。
url 和 body 同時(shí)提交
方案一(失敗)
在 path
方法中拼接 url 的參數(shù)深胳,在 task
中提交 body 的參數(shù)绰疤。
public enum LiveShowRequest {
case anchorHeartBeat(userID: String,
roomID: String)
}
extension LiveShowRequest: TargetType {
public var path: String {
switch self {
case .anchorHeartBeat(let userID, _):
return "anchor_heartbeat?userID=\(userID)"
}
}
public var task: Task {
switch self {
case let .anchorHeartBeat(_, roomID):
var params = ["roomID": roomID] as [String : Any]
return .requestParameters(parameters: params, encoding: JSONEncoding.default)
}
}
}
經(jīng)過測試,這樣是不行的舞终,因?yàn)?Moya 會對 path
的返回值進(jìn)行編碼轻庆,導(dǎo)致用于拼接參數(shù)的 ?
被編碼成了 %3f
,服務(wù)器無法解析參數(shù)了敛劝。
方案二(成功)
在 task
中使用 requestCompositeParameters
余爆,可以同時(shí)設(shè)置 bodyParameters
和 urlParameters
。
extension LiveShowRequest: TargetType {
public var path: String {
switch self {
case .anchorHeartBeat(let userID, _):
return "anchor_heartbeat"
}
}
public var task: Task {
switch self {
case let .anchorHeartBeat(userID, roomID):
var params = ["roomID": roomID] as [String : Any]
var urlParameters = ["userID": userID]
return .requestCompositeParameters(bodyParameters: params,
bodyEncoding: JSONEncoding.default,
urlParameters: urlParameters)
}
}
}
這種方式可以處理同時(shí)傳入 url 和 body 參數(shù)的情況夸盟。
方法三(成功)
在 baseURL 中拼接 url 參數(shù)蛾方,在 task 中設(shè)置 body 參數(shù),可以避免方法一中 ?
被編碼的問題满俗。
extension LiveShowRequest: TargetType {
public var baseURL: URL {
switch self {
case let .anchorHeartBeat(userID, _):
return URL(string: BaseURL + "?userID=\(userID)")!
}
}
public var path: String {
switch self {
case .anchorHeartBeat:
return "anchor_heartbeat"
}
}
public var task: Task {
switch self {
case let .anchorHeartBeat(_, roomID):
var params = ["roomID": roomID] as [String : Any]
return .requestParameters(parameters: params, encoding: JSONEncoding.default)
}
}
url 參數(shù)的編碼問題
假如傳入的 url 參數(shù)當(dāng)中有 *
转捕,比如上面的例子當(dāng)中的 userID 為 0558eba*1400489990
,Moya 會將 *
轉(zhuǎn)換為 %2A
唆垃,也就是進(jìn)行了 url 編碼。但是 *
本身不需要進(jìn)行 url 編碼痘儡,Moay 為什么要對 *
進(jìn)行編碼呢辕万?
在 Moya 當(dāng)中,url 的參數(shù)是通過 URLEncoding
進(jìn)行編碼的沉删。
public struct URLEncoding: ParameterEncoding {
/// Returns a percent-escaped string following RFC 3986 for a query string key or value.
///
/// RFC 3986 states that the following characters are "reserved" characters.
///
/// - General Delimiters: ":", "#", "[", "]", "@", "?", "/"
/// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
///
/// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
/// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
/// should be percent-escaped in the query string.
///
/// - parameter string: The string to be percent-escaped.
///
/// - returns: The percent-escaped string.
public func escape(_ string: String) -> String {
let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
let subDelimitersToEncode = "!$&'()*+,;="
var allowedCharacterSet = CharacterSet.urlQueryAllowed
allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
var escaped = ""
//==========================================================================================================
//
// Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few
// hundred Chinese characters causes various malloc error crashes. To avoid this issue until iOS 8 is no
// longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more
// info, please refer to:
//
// - https://github.com/Alamofire/Alamofire/issues/206
//
//==========================================================================================================
if #available(iOS 8.3, *) {
escaped = string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? string
} else {
let batchSize = 50
var index = string.startIndex
while index != string.endIndex {
let startIndex = index
let endIndex = string.index(index, offsetBy: batchSize, limitedBy: string.endIndex) ?? string.endIndex
let range = startIndex..<endIndex
let substring = string[range]
escaped += substring.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? String(substring)
index = endIndex
}
}
return escaped
}
}
拼接進(jìn) URL 的參數(shù)的 key 和 value渐尿,都會調(diào)用 escape
方法進(jìn)行編碼。escape
方法根據(jù) RFC 3986
返回百分號轉(zhuǎn)移的字符串矾瑰。在調(diào)用 addingPercentEncoding
之前砖茸,先移除了 CharacterSet.urlQueryAllowed
中包含在 generalDelimitersToEncode
和 subDelimitersToEncode
中的字符。
let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
let subDelimitersToEncode = "!$&'()*+,;="
var allowedCharacterSet = CharacterSet.urlQueryAllowed
allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
可以通過下面的擴(kuò)展方法查看包含在 CharacterSet.urlQueryAllowed
的字符串殴穴。(方法來自 stackoverflow)
extension CharacterSet {
func characters() -> [Character] {
// A Unicode scalar is any Unicode code point in the range U+0000 to U+D7FF inclusive or U+E000 to U+10FFFF inclusive.
return codePoints().compactMap { UnicodeScalar($0) }.map { Character($0) }
}
func codePoints() -> [Int] {
var result: [Int] = []
var plane = 0
// following documentation at https://developer.apple.com/documentation/foundation/nscharacterset/1417719-bitmaprepresentation
for (i, w) in bitmapRepresentation.enumerated() {
let k = i % 0x2001
if k == 0x2000 {
// plane index byte
plane = Int(w) << 13
continue
}
let base = (plane + k) << 3
for j in 0 ..< 8 where w & 1 << j != 0 {
result.append(base + j)
}
}
return result
}
}
// 使用方法
var allowedCharacterSet = CharacterSet.urlQueryAllowed
debugPrint(allowedCharacterSet.characters())
// 結(jié)果
["!", "$", "&", "\'", "(", ")", "*", "+", ",", "-", ".", "/", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ":", ";", "=", "?", "@", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "_", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "~"]
如果凉夯,恰好 url 參數(shù)中有這些字符,又不想被編碼采幌,要怎么處理呢劲够?只能自定義一個(gè)符合 ParameterEncoding
的類型,實(shí)現(xiàn)自定義編碼方式休傍。
下面的 MultipleEncoding 由 https://github.com/Moya/Moya/issues/1059 提供的思路實(shí)現(xiàn)征绎。初始化 MultipleEncoding 時(shí),通過 urlParameters 定義需要被 url 編碼的 key磨取,其他的 key 則為編碼為 body人柿。
struct MultipleEncoding : ParameterEncoding {
var urlParameters: [String]?
init(urlParameters:[String]?) {
self.urlParameters = urlParameters
}
func encode(_ urlRequest: Alamofire.URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
guard let parameters = parameters else { return urlRequest as! URLRequest }
var urlParams: [String: Any] = [:]
var jsonParams: [String: Any] = [:]
parameters.forEach { (key: String, value: Any) in
if urlParameters?.contains(key) ?? false {
urlParams[key] = value
} else {
jsonParams[key] = value
}
}
// Encode URL Params
// 過程和 URLEncoding.queryString.encode(urlRequest, with: urlParams) 一致
var urlRequest = try urlRequest.asURLRequest()
if let url = urlRequest.url {
if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !urlParams.isEmpty {
let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(urlParams)
urlComponents.percentEncodedQuery = percentEncodedQuery
urlRequest.url = urlComponents.url
}
}
//Encode JSON
return try JSONEncoding.default.encode(urlRequest, with: jsonParams)
}
private func query(_ parameters: [String: Any]) -> String {
// 直接復(fù)制 URLEncoding 中的方法
}
public func queryComponents(fromKey key: String, value: Any) -> [(String, String)] {
// 直接復(fù)制 URLEncoding 中的方法
}
// escape 只需要根據(jù)需要移出不希望被編碼的字符
public func escape(_ string: String) -> String {
let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
let subDelimitersToEncode = "!$&'()*+,;="
var allowedCharacterSet = CharacterSet.urlQueryAllowed
// allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
// 下面的代碼和 URLEncoding 中的方法一致
}
}
使用時(shí)如下柴墩。
extension LiveShowRequest: TargetType {
public var path: String {
switch self {
case .anchorHeartBeat(let userID, _):
return "anchor_heartbeat"
}
}
public var task: Task {
switch self {
case let .anchorHeartBeat(userID, roomID):
var params = ["roomID": roomID,
"userID": userID,
] as [String : Any]
let urlParameters = ["userID"]
return .requestParameters(parameters: params, encoding: MultipleEncoding(urlParameters: urlParameters))
}
}
}
這樣就自定了 url 和 body 編碼的整個(gè)過程。