ParameterEncoding.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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(using: .utf8, allowLossyConversion: false)
  121. }
  122. return urlRequest
  123. }
  124. /// Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion.
  125. ///
  126. /// - parameter key: The key of the query component.
  127. /// - parameter value: The value of the query component.
  128. ///
  129. /// - returns: The percent-escaped, URL encoded query string components.
  130. public func queryComponents(fromKey key: String, value: Any) -> [(String, String)] {
  131. var components: [(String, String)] = []
  132. if let dictionary = value as? [String: Any] {
  133. for (nestedKey, value) in dictionary {
  134. components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value)
  135. }
  136. } else if let array = value as? [Any] {
  137. for value in array {
  138. components += queryComponents(fromKey: "\(key)[]", value: value)
  139. }
  140. } else if let bool = value as? Bool {
  141. components.append((escape(key), escape((bool ? "1" : "0"))))
  142. } else {
  143. components.append((escape(key), escape("\(value)")))
  144. }
  145. return components
  146. }
  147. /// Returns a percent-escaped string following RFC 3986 for a query string key or value.
  148. ///
  149. /// RFC 3986 states that the following characters are "reserved" characters.
  150. ///
  151. /// - General Delimiters: ":", "#", "[", "]", "@", "?", "/"
  152. /// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
  153. ///
  154. /// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
  155. /// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
  156. /// should be percent-escaped in the query string.
  157. ///
  158. /// - parameter string: The string to be percent-escaped.
  159. ///
  160. /// - returns: The percent-escaped string.
  161. public func escape(_ string: String) -> String {
  162. let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
  163. let subDelimitersToEncode = "!$&'()*+,;="
  164. var allowedCharacterSet = CharacterSet.urlQueryAllowed
  165. allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
  166. return string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? string
  167. }
  168. private func query(_ parameters: [String: Any]) -> String {
  169. var components: [(String, String)] = []
  170. for key in parameters.keys.sorted(by: <) {
  171. let value = parameters[key]!
  172. components += queryComponents(fromKey: key, value: value)
  173. }
  174. return components.map { "\($0)=\($1)" }.joined(separator: "&")
  175. }
  176. private func encodesParametersInURL(with method: HTTPMethod) -> Bool {
  177. switch destination {
  178. case .queryString:
  179. return true
  180. case .httpBody:
  181. return false
  182. default:
  183. break
  184. }
  185. switch method {
  186. case .get, .head, .delete:
  187. return true
  188. default:
  189. return false
  190. }
  191. }
  192. }
  193. // MARK: -
  194. /// Uses `JSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the
  195. /// request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`.
  196. public struct JSONEncoding: ParameterEncoding {
  197. // MARK: Properties
  198. /// Returns a `JSONEncoding` instance with default writing options.
  199. public static var `default`: JSONEncoding { return JSONEncoding() }
  200. /// Returns a `JSONEncoding` instance with `.prettyPrinted` writing options.
  201. public static var prettyPrinted: JSONEncoding { return JSONEncoding(options: .prettyPrinted) }
  202. /// The options for writing the parameters as JSON data.
  203. public let options: JSONSerialization.WritingOptions
  204. // MARK: Initialization
  205. /// Creates a `JSONEncoding` instance using the specified options.
  206. ///
  207. /// - parameter options: The options for writing the parameters as JSON data.
  208. ///
  209. /// - returns: The new `JSONEncoding` instance.
  210. public init(options: JSONSerialization.WritingOptions = []) {
  211. self.options = options
  212. }
  213. // MARK: Encoding
  214. /// Creates a URL request by encoding parameters and applying them onto an existing request.
  215. ///
  216. /// - parameter urlRequest: The request to have parameters applied.
  217. /// - parameter parameters: The parameters to apply.
  218. ///
  219. /// - throws: An `AFError.parameterEncodingFailed` error if encoding fails.
  220. ///
  221. /// - returns: The encoded request.
  222. public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
  223. var urlRequest = urlRequest.urlRequest
  224. guard let parameters = parameters else { return urlRequest }
  225. do {
  226. let data = try JSONSerialization.data(withJSONObject: parameters, options: options)
  227. if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
  228. urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
  229. }
  230. urlRequest.httpBody = data
  231. } catch {
  232. throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
  233. }
  234. return urlRequest
  235. }
  236. }
  237. // MARK: -
  238. /// Uses `PropertyListSerialization` to create a plist representation of the parameters object, according to the
  239. /// associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header
  240. /// field of an encoded request is set to `application/x-plist`.
  241. public struct PropertyListEncoding: ParameterEncoding {
  242. // MARK: Properties
  243. /// Returns a default `PropertyListEncoding` instance.
  244. public static var `default`: PropertyListEncoding { return PropertyListEncoding() }
  245. /// Returns a `PropertyListEncoding` instance with xml formatting and default writing options.
  246. public static var xml: PropertyListEncoding { return PropertyListEncoding(format: .xml) }
  247. /// Returns a `PropertyListEncoding` instance with binary formatting and default writing options.
  248. public static var binary: PropertyListEncoding { return PropertyListEncoding(format: .binary) }
  249. /// The property list serialization format.
  250. public let format: PropertyListSerialization.PropertyListFormat
  251. /// The options for writing the parameters as plist data.
  252. public let options: PropertyListSerialization.WriteOptions
  253. // MARK: Initialization
  254. /// Creates a `PropertyListEncoding` instance using the specified format and options.
  255. ///
  256. /// - parameter format: The property list serialization format.
  257. /// - parameter options: The options for writing the parameters as plist data.
  258. ///
  259. /// - returns: The new `PropertyListEncoding` instance.
  260. public init(
  261. format: PropertyListSerialization.PropertyListFormat = .xml,
  262. options: PropertyListSerialization.WriteOptions = 0)
  263. {
  264. self.format = format
  265. self.options = options
  266. }
  267. // MARK: Encoding
  268. /// Creates a URL request by encoding parameters and applying them onto an existing request.
  269. ///
  270. /// - parameter urlRequest: The request to have parameters applied.
  271. /// - parameter parameters: The parameters to apply.
  272. ///
  273. /// - throws: An `AFError.parameterEncodingFailed` error if encoding fails.
  274. ///
  275. /// - returns: The encoded request.
  276. public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
  277. var urlRequest = urlRequest.urlRequest
  278. guard let parameters = parameters else { return urlRequest }
  279. do {
  280. let data = try PropertyListSerialization.data(
  281. fromPropertyList: parameters,
  282. format: format,
  283. options: options
  284. )
  285. if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
  286. urlRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
  287. }
  288. urlRequest.httpBody = data
  289. } catch {
  290. throw AFError.parameterEncodingFailed(reason: .propertyListEncodingFailed(error: error))
  291. }
  292. return urlRequest
  293. }
  294. }