ParameterEncoding.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. //
  2. // ParameterEncoding.swift
  3. //
  4. // Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. import Foundation
  25. /// A dictionary of parameters to apply to a `URLRequest`.
  26. public typealias Parameters = [String: Any]
  27. /// A type used to define how a set of parameters are applied to a `URLRequest`.
  28. public protocol ParameterEncoding {
  29. /// Creates a `URLRequest` by encoding parameters and applying them on the passed request.
  30. ///
  31. /// - Parameters:
  32. /// - urlRequest: `URLRequestConvertible` value onto which parameters will be encoded.
  33. /// - parameters: `Parameters` to encode onto the request.
  34. ///
  35. /// - Returns: The encoded `URLRequest`.
  36. /// - Throws: Any `Error` produced during parameter encoding.
  37. func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest
  38. }
  39. // MARK: -
  40. /// Creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP
  41. /// body of the URL request. Whether the query string is set or appended to any existing URL query string or set as
  42. /// the HTTP body depends on the destination of the encoding.
  43. ///
  44. /// The `Content-Type` HTTP header field of an encoded request with HTTP body is set to
  45. /// `application/x-www-form-urlencoded; charset=utf-8`.
  46. ///
  47. /// There is no published specification for how to encode collection types. By default the convention of appending
  48. /// `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for
  49. /// nested dictionary values (`foo[bar]=baz`) is used. Optionally, `ArrayEncoding` can be used to omit the
  50. /// square brackets appended to array keys.
  51. ///
  52. /// `BoolEncoding` can be used to configure how boolean values are encoded. The default behavior is to encode
  53. /// `true` as 1 and `false` as 0.
  54. public struct URLEncoding: ParameterEncoding {
  55. // MARK: Helper Types
  56. /// Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the
  57. /// resulting URL request.
  58. public enum Destination {
  59. /// Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE` requests and
  60. /// sets as the HTTP body for requests with any other HTTP method.
  61. case methodDependent
  62. /// Sets or appends encoded query string result to existing query string.
  63. case queryString
  64. /// Sets encoded query string result as the HTTP body of the URL request.
  65. case httpBody
  66. func encodesParametersInURL(for method: HTTPMethod) -> Bool {
  67. switch self {
  68. case .methodDependent: return [.get, .head, .delete].contains(method)
  69. case .queryString: return true
  70. case .httpBody: return false
  71. }
  72. }
  73. }
  74. /// Configures how `Array` parameters are encoded.
  75. public enum ArrayEncoding {
  76. /// An empty set of square brackets is appended to the key for every value. This is the default behavior.
  77. case brackets
  78. /// No brackets are appended. The key is encoded as is.
  79. case noBrackets
  80. /// Brackets containing the item index are appended. This matches the jQuery and Node.js behavior.
  81. case indexInBrackets
  82. /// Provide a custom array key encoding with the given closure.
  83. case custom((_ key: String, _ index: Int) -> String)
  84. func encode(key: String, atIndex index: Int) -> String {
  85. switch self {
  86. case .brackets:
  87. return "\(key)[]"
  88. case .noBrackets:
  89. return key
  90. case .indexInBrackets:
  91. return "\(key)[\(index)]"
  92. case let .custom(encoding):
  93. return encoding(key, index)
  94. }
  95. }
  96. }
  97. /// Configures how `Bool` parameters are encoded.
  98. public enum BoolEncoding {
  99. /// Encode `true` as `1` and `false` as `0`. This is the default behavior.
  100. case numeric
  101. /// Encode `true` and `false` as string literals.
  102. case literal
  103. func encode(value: Bool) -> String {
  104. switch self {
  105. case .numeric:
  106. return value ? "1" : "0"
  107. case .literal:
  108. return value ? "true" : "false"
  109. }
  110. }
  111. }
  112. // MARK: Properties
  113. /// Returns a default `URLEncoding` instance with a `.methodDependent` destination.
  114. public static var `default`: URLEncoding { URLEncoding() }
  115. /// Returns a `URLEncoding` instance with a `.queryString` destination.
  116. public static var queryString: URLEncoding { URLEncoding(destination: .queryString) }
  117. /// Returns a `URLEncoding` instance with an `.httpBody` destination.
  118. public static var httpBody: URLEncoding { URLEncoding(destination: .httpBody) }
  119. /// The destination defining where the encoded query string is to be applied to the URL request.
  120. public let destination: Destination
  121. /// The encoding to use for `Array` parameters.
  122. public let arrayEncoding: ArrayEncoding
  123. /// The encoding to use for `Bool` parameters.
  124. public let boolEncoding: BoolEncoding
  125. // MARK: Initialization
  126. /// Creates an instance using the specified parameters.
  127. ///
  128. /// - Parameters:
  129. /// - destination: `Destination` defining where the encoded query string will be applied. `.methodDependent` by
  130. /// default.
  131. /// - arrayEncoding: `ArrayEncoding` to use. `.brackets` by default.
  132. /// - boolEncoding: `BoolEncoding` to use. `.numeric` by default.
  133. public init(destination: Destination = .methodDependent,
  134. arrayEncoding: ArrayEncoding = .brackets,
  135. boolEncoding: BoolEncoding = .numeric) {
  136. self.destination = destination
  137. self.arrayEncoding = arrayEncoding
  138. self.boolEncoding = boolEncoding
  139. }
  140. // MARK: Encoding
  141. public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
  142. var urlRequest = try urlRequest.asURLRequest()
  143. guard let parameters = parameters else { return urlRequest }
  144. if let method = urlRequest.method, destination.encodesParametersInURL(for: method) {
  145. guard let url = urlRequest.url else {
  146. throw AFError.parameterEncodingFailed(reason: .missingURL)
  147. }
  148. if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty {
  149. let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters)
  150. urlComponents.percentEncodedQuery = percentEncodedQuery
  151. urlRequest.url = urlComponents.url
  152. }
  153. } else {
  154. if urlRequest.headers["Content-Type"] == nil {
  155. urlRequest.headers.update(.contentType("application/x-www-form-urlencoded; charset=utf-8"))
  156. }
  157. urlRequest.httpBody = Data(query(parameters).utf8)
  158. }
  159. return urlRequest
  160. }
  161. /// Creates a percent-escaped, URL encoded query string components from the given key-value pair recursively.
  162. ///
  163. /// - Parameters:
  164. /// - key: Key of the query component.
  165. /// - value: Value of the query component.
  166. ///
  167. /// - Returns: The percent-escaped, URL encoded query string components.
  168. public func queryComponents(fromKey key: String, value: Any) -> [(String, String)] {
  169. var components: [(String, String)] = []
  170. switch value {
  171. case let dictionary as [String: Any]:
  172. for (nestedKey, value) in dictionary {
  173. components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value)
  174. }
  175. case let array as [Any]:
  176. for (index, value) in array.enumerated() {
  177. components += queryComponents(fromKey: arrayEncoding.encode(key: key, atIndex: index), value: value)
  178. }
  179. case let number as NSNumber:
  180. if number.isBool {
  181. components.append((escape(key), escape(boolEncoding.encode(value: number.boolValue))))
  182. } else {
  183. components.append((escape(key), escape("\(number)")))
  184. }
  185. case let bool as Bool:
  186. components.append((escape(key), escape(boolEncoding.encode(value: bool))))
  187. default:
  188. components.append((escape(key), escape("\(value)")))
  189. }
  190. return components
  191. }
  192. /// Creates a percent-escaped string following RFC 3986 for a query string key or value.
  193. ///
  194. /// - Parameter string: `String` to be percent-escaped.
  195. ///
  196. /// - Returns: The percent-escaped `String`.
  197. public func escape(_ string: String) -> String {
  198. string.addingPercentEncoding(withAllowedCharacters: .afURLQueryAllowed) ?? string
  199. }
  200. private func query(_ parameters: [String: Any]) -> String {
  201. var components: [(String, String)] = []
  202. for key in parameters.keys.sorted(by: <) {
  203. let value = parameters[key]!
  204. components += queryComponents(fromKey: key, value: value)
  205. }
  206. return components.map { "\($0)=\($1)" }.joined(separator: "&")
  207. }
  208. }
  209. // MARK: -
  210. /// Uses `JSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the
  211. /// request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`.
  212. public struct JSONEncoding: ParameterEncoding {
  213. public enum Error: Swift.Error {
  214. case invalidJSONObject
  215. }
  216. // MARK: Properties
  217. /// Returns a `JSONEncoding` instance with default writing options.
  218. public static var `default`: JSONEncoding { JSONEncoding() }
  219. /// Returns a `JSONEncoding` instance with `.prettyPrinted` writing options.
  220. public static var prettyPrinted: JSONEncoding { JSONEncoding(options: .prettyPrinted) }
  221. /// The options for writing the parameters as JSON data.
  222. public let options: JSONSerialization.WritingOptions
  223. // MARK: Initialization
  224. /// Creates an instance using the specified `WritingOptions`.
  225. ///
  226. /// - Parameter options: `JSONSerialization.WritingOptions` to use.
  227. public init(options: JSONSerialization.WritingOptions = []) {
  228. self.options = options
  229. }
  230. // MARK: Encoding
  231. public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
  232. var urlRequest = try urlRequest.asURLRequest()
  233. guard let parameters = parameters else { return urlRequest }
  234. guard JSONSerialization.isValidJSONObject(parameters) else {
  235. throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: Error.invalidJSONObject))
  236. }
  237. do {
  238. let data = try JSONSerialization.data(withJSONObject: parameters, options: options)
  239. if urlRequest.headers["Content-Type"] == nil {
  240. urlRequest.headers.update(.contentType("application/json"))
  241. }
  242. urlRequest.httpBody = data
  243. } catch {
  244. throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
  245. }
  246. return urlRequest
  247. }
  248. /// Encodes any JSON compatible object into a `URLRequest`.
  249. ///
  250. /// - Parameters:
  251. /// - urlRequest: `URLRequestConvertible` value into which the object will be encoded.
  252. /// - jsonObject: `Any` value (must be JSON compatible` to be encoded into the `URLRequest`. `nil` by default.
  253. ///
  254. /// - Returns: The encoded `URLRequest`.
  255. /// - Throws: Any `Error` produced during encoding.
  256. public func encode(_ urlRequest: URLRequestConvertible, withJSONObject jsonObject: Any? = nil) throws -> URLRequest {
  257. var urlRequest = try urlRequest.asURLRequest()
  258. guard let jsonObject = jsonObject else { return urlRequest }
  259. guard JSONSerialization.isValidJSONObject(jsonObject) else {
  260. throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: Error.invalidJSONObject))
  261. }
  262. do {
  263. let data = try JSONSerialization.data(withJSONObject: jsonObject, options: options)
  264. if urlRequest.headers["Content-Type"] == nil {
  265. urlRequest.headers.update(.contentType("application/json"))
  266. }
  267. urlRequest.httpBody = data
  268. } catch {
  269. throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
  270. }
  271. return urlRequest
  272. }
  273. }
  274. extension JSONEncoding.Error {
  275. public var localizedDescription: String {
  276. """
  277. Invalid JSON object provided for parameter or object encoding. \
  278. This is most likely due to a value which can't be represented in Objective-C.
  279. """
  280. }
  281. }
  282. // MARK: -
  283. extension NSNumber {
  284. fileprivate var isBool: Bool {
  285. // Use Obj-C type encoding to check whether the underlying type is a `Bool`, as it's guaranteed as part of
  286. // swift-corelibs-foundation, per [this discussion on the Swift forums](https://forums.swift.org/t/alamofire-on-linux-possible-but-not-release-ready/34553/22).
  287. String(cString: objCType) == "c"
  288. }
  289. }