ParameterEncoding.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. //
  2. // ParameterEncoding.swift
  3. //
  4. // Copyright (c) 2014-2016 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. /// HTTP method definitions.
  26. ///
  27. /// See https://tools.ietf.org/html/rfc7231#section-4.3
  28. public enum HTTPMethod: String {
  29. case options = "OPTIONS"
  30. case get = "GET"
  31. case head = "HEAD"
  32. case post = "POST"
  33. case put = "PUT"
  34. case patch = "PATCH"
  35. case delete = "DELETE"
  36. case trace = "TRACE"
  37. case connect = "CONNECT"
  38. }
  39. // MARK: -
  40. /// A dictionary of parameters to apply to a `URLRequest`.
  41. public typealias Parameters = [String: Any]
  42. /// A type used to define how a set of parameters are applied to a `URLRequest`.
  43. public protocol ParameterEncoding {
  44. /// Creates a URL request by encoding parameters and applying them onto an existing request.
  45. ///
  46. /// - parameter urlRequest: The request to have parameters applied.
  47. /// - parameter parameters: The parameters to apply.
  48. ///
  49. /// - throws: An `AFError.parameterEncodingFailed` error if encoding fails.
  50. ///
  51. /// - returns: The encoded request.
  52. func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest
  53. }
  54. // MARK: -
  55. /// Creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP
  56. /// body of the URL request. Whether the query string is set or appended to any existing URL query string or set as
  57. /// the HTTP body depends on the destination of the encoding.
  58. ///
  59. /// The `Content-Type` HTTP header field of an encoded request with HTTP body is set to
  60. /// `application/x-www-form-urlencoded; charset=utf-8`. Since there is no published specification for how to encode
  61. /// collection types, the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending
  62. /// the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`).
  63. public struct URLEncoding: ParameterEncoding {
  64. // MARK: Helper Types
  65. /// Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the
  66. /// resulting URL request.
  67. ///
  68. /// - methodDependent: Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE`
  69. /// requests and sets as the HTTP body for requests with any other HTTP method.
  70. /// - queryString: Sets or appends encoded query string result to existing query string.
  71. /// - httpBody: Sets encoded query string result as the HTTP body of the URL request.
  72. public enum Destination {
  73. case methodDependent, queryString, httpBody
  74. }
  75. // MARK: Properties
  76. /// Returns a default `URLEncoding` instance.
  77. public static var `default`: URLEncoding { return URLEncoding() }
  78. /// Returns a `URLEncoding` instance with a `.methodDependent` destination.
  79. public static var methodDependent: URLEncoding { return URLEncoding() }
  80. /// Returns a `URLEncoding` instance with a `.queryString` destination.
  81. public static var queryString: URLEncoding { return URLEncoding(destination: .queryString) }
  82. /// Returns a `URLEncoding` instance with an `.httpBody` destination.
  83. public static var httpBody: URLEncoding { return URLEncoding(destination: .httpBody) }
  84. /// The destination defining where the encoded query string is to be applied to the URL request.
  85. public let destination: Destination
  86. // MARK: Initialization
  87. /// Creates a `URLEncoding` instance using the specified destination.
  88. ///
  89. /// - parameter destination: The destination defining where the encoded query string is to be applied.
  90. ///
  91. /// - returns: The new `URLEncoding` instance.
  92. public init(destination: Destination = .methodDependent) {
  93. self.destination = destination
  94. }
  95. // MARK: Encoding
  96. /// Creates a URL request by encoding parameters and applying them onto an existing request.
  97. ///
  98. /// - parameter urlRequest: The request to have parameters applied.
  99. /// - parameter parameters: The parameters to apply.
  100. ///
  101. /// - throws: An `AFError.parameterEncodingFailed` error if encoding fails.
  102. ///
  103. /// - returns: The encoded request.
  104. public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
  105. var urlRequest = urlRequest.urlRequest
  106. guard let parameters = parameters else { return urlRequest }
  107. if let method = HTTPMethod(rawValue: urlRequest.httpMethod ?? "GET"), encodesParametersInURL(with: method) {
  108. guard let url = urlRequest.url else {
  109. throw AFError.parameterEncodingFailed(reason: .missingURL)
  110. }
  111. if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty {
  112. let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters)
  113. urlComponents.percentEncodedQuery = percentEncodedQuery
  114. urlRequest.url = urlComponents.url
  115. }
  116. } else {
  117. if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
  118. urlRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
  119. }
  120. urlRequest.httpBody = query(parameters).data(
  121. using: String.Encoding.utf8,
  122. allowLossyConversion: false
  123. )
  124. }
  125. return urlRequest
  126. }
  127. /// Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion.
  128. ///
  129. /// - parameter key: The key of the query component.
  130. /// - parameter value: The value of the query component.
  131. ///
  132. /// - returns: The percent-escaped, URL encoded query string components.
  133. public func queryComponents(fromKey key: String, value: Any) -> [(String, String)] {
  134. var components: [(String, String)] = []
  135. if let dictionary = value as? [String: Any] {
  136. for (nestedKey, value) in dictionary {
  137. components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value)
  138. }
  139. } else if let array = value as? [Any] {
  140. for value in array {
  141. components += queryComponents(fromKey: "\(key)[]", value: value)
  142. }
  143. } else if let bool = value as? Bool {
  144. components.append((escape(key), escape((bool ? "1" : "0"))))
  145. } else {
  146. components.append((escape(key), escape("\(value)")))
  147. }
  148. return components
  149. }
  150. /// Returns a percent-escaped string following RFC 3986 for a query string key or value.
  151. ///
  152. /// RFC 3986 states that the following characters are "reserved" characters.
  153. ///
  154. /// - General Delimiters: ":", "#", "[", "]", "@", "?", "/"
  155. /// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
  156. ///
  157. /// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
  158. /// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
  159. /// should be percent-escaped in the query string.
  160. ///
  161. /// - parameter string: The string to be percent-escaped.
  162. ///
  163. /// - returns: The percent-escaped string.
  164. public func escape(_ string: String) -> String {
  165. let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
  166. let subDelimitersToEncode = "!$&'()*+,;="
  167. var allowedCharacterSet = CharacterSet.urlQueryAllowed
  168. allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
  169. return string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? string
  170. }
  171. private func query(_ parameters: [String: Any]) -> String {
  172. var components: [(String, String)] = []
  173. for key in parameters.keys.sorted(by: <) {
  174. let value = parameters[key]!
  175. components += queryComponents(fromKey: key, value: value)
  176. }
  177. return components.map { "\($0)=\($1)" }.joined(separator: "&")
  178. }
  179. private func encodesParametersInURL(with method: HTTPMethod) -> Bool {
  180. switch destination {
  181. case .queryString:
  182. return true
  183. case .httpBody:
  184. return false
  185. default:
  186. break
  187. }
  188. switch method {
  189. case .get, .head, .delete:
  190. return true
  191. default:
  192. return false
  193. }
  194. }
  195. }
  196. // MARK: -
  197. /// Uses `JSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the
  198. /// request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`.
  199. public struct JSONEncoding: ParameterEncoding {
  200. // MARK: Properties
  201. /// Returns a `JSONEncoding` instance with default writing options.
  202. public static var `default`: JSONEncoding { return JSONEncoding() }
  203. /// Returns a `JSONEncoding` instance with `.prettyPrinted` writing options.
  204. public static var prettyPrinted: JSONEncoding { return JSONEncoding(options: .prettyPrinted) }
  205. /// The options for writing the parameters as JSON data.
  206. public let options: JSONSerialization.WritingOptions
  207. // MARK: Initialization
  208. /// Creates a `JSONEncoding` instance using the specified options.
  209. ///
  210. /// - parameter options: The options for writing the parameters as JSON data.
  211. ///
  212. /// - returns: The new `JSONEncoding` instance.
  213. public init(options: JSONSerialization.WritingOptions = []) {
  214. self.options = options
  215. }
  216. // MARK: Encoding
  217. /// Creates a URL request by encoding parameters and applying them onto an existing request.
  218. ///
  219. /// - parameter urlRequest: The request to have parameters applied.
  220. /// - parameter parameters: The parameters to apply.
  221. ///
  222. /// - throws: An `AFError.parameterEncodingFailed` error if encoding fails.
  223. ///
  224. /// - returns: The encoded request.
  225. public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
  226. var urlRequest = urlRequest.urlRequest
  227. guard let parameters = parameters else { return urlRequest }
  228. do {
  229. let data = try JSONSerialization.data(withJSONObject: parameters, options: options)
  230. if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
  231. urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
  232. }
  233. urlRequest.httpBody = data
  234. } catch {
  235. throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
  236. }
  237. return urlRequest
  238. }
  239. }
  240. // MARK: -
  241. /// Uses `PropertyListSerialization` to create a plist representation of the parameters object, according to the
  242. /// associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header
  243. /// field of an encoded request is set to `application/x-plist`.
  244. public struct PropertyListEncoding: ParameterEncoding {
  245. // MARK: Properties
  246. /// Returns a default `PropertyListEncoding` instance.
  247. public static var `default`: PropertyListEncoding { return PropertyListEncoding() }
  248. /// Returns a `PropertyListEncoding` instance with xml formatting and default writing options.
  249. public static var xml: PropertyListEncoding { return PropertyListEncoding(format: .xml) }
  250. /// Returns a `PropertyListEncoding` instance with binary formatting and default writing options.
  251. public static var binary: PropertyListEncoding { return PropertyListEncoding(format: .binary) }
  252. /// The property list serialization format.
  253. public let format: PropertyListSerialization.PropertyListFormat
  254. /// The options for writing the parameters as plist data.
  255. public let options: PropertyListSerialization.WriteOptions
  256. // MARK: Initialization
  257. /// Creates a `PropertyListEncoding` instance using the specified format and options.
  258. ///
  259. /// - parameter format: The property list serialization format.
  260. /// - parameter options: The options for writing the parameters as plist data.
  261. ///
  262. /// - returns: The new `PropertyListEncoding` instance.
  263. public init(
  264. format: PropertyListSerialization.PropertyListFormat = .xml,
  265. options: PropertyListSerialization.WriteOptions = 0)
  266. {
  267. self.format = format
  268. self.options = options
  269. }
  270. // MARK: Encoding
  271. /// Creates a URL request by encoding parameters and applying them onto an existing request.
  272. ///
  273. /// - parameter urlRequest: The request to have parameters applied.
  274. /// - parameter parameters: The parameters to apply.
  275. ///
  276. /// - throws: An `AFError.parameterEncodingFailed` error if encoding fails.
  277. ///
  278. /// - returns: The encoded request.
  279. public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
  280. var urlRequest = urlRequest.urlRequest
  281. guard let parameters = parameters else { return urlRequest }
  282. do {
  283. let data = try PropertyListSerialization.data(
  284. fromPropertyList: parameters,
  285. format: format,
  286. options: options
  287. )
  288. if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
  289. urlRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
  290. }
  291. urlRequest.httpBody = data
  292. } catch {
  293. throw AFError.parameterEncodingFailed(reason: .propertyListEncodingFailed(error: error))
  294. }
  295. return urlRequest
  296. }
  297. }