ParameterEncoding.swift 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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. /// Used to specify the way in which a set of parameters are applied to a URL request.
  41. ///
  42. /// - url: Creates a query string to be set as or appended to any existing URL query for `GET`, `HEAD`,
  43. /// and `DELETE` requests, or set as the body for requests with any other HTTP method. The
  44. /// `Content-Type` HTTP header field of an encoded request with HTTP body is set to
  45. /// `application/x-www-form-urlencoded; charset=utf-8`. Since there is no published specification
  46. /// for how to encode collection types, the convention of appending `[]` to the key for array
  47. /// values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested
  48. /// dictionary values (`foo[bar]=baz`).
  49. ///
  50. /// - urlEncodedInURL: Creates query string to be set as or appended to any existing URL query. Uses the same
  51. /// implementation as the `.url` case, but always applies the encoded result to the URL.
  52. ///
  53. /// - json: Uses `JSONSerialization` to create a JSON representation of the parameters object, which is
  54. /// set as the body of the request. The `Content-Type` HTTP header field of an encoded request is
  55. /// set to `application/json`.
  56. ///
  57. /// - propertyList: Uses `PropertyListSerialization` to create a plist representation of the parameters object,
  58. /// according to the associated format and write options values, which is set as the body of the
  59. /// request. The `Content-Type` HTTP header field of an encoded request is set to
  60. /// `application/x-plist`.
  61. ///
  62. /// - custom: Uses the associated closure value to construct a new request given an existing request and
  63. /// parameters.
  64. public enum ParameterEncoding {
  65. case url
  66. case urlEncodedInURL
  67. case json
  68. case propertyList(PropertyListSerialization.PropertyListFormat, PropertyListSerialization.WriteOptions)
  69. case custom((URLRequestConvertible, [String: Any]?) throws -> URLRequest)
  70. /// Creates a URL request by encoding parameters and applying them onto an existing request.
  71. ///
  72. /// - parameter urlRequest: The request to have parameters applied.
  73. /// - parameter parameters: The parameters to apply.
  74. ///
  75. /// - throws: An `AFError.parameterEncodingFailed` error if json or property list serialization fails.
  76. ///
  77. /// - returns: A tuple containing the constructed request and the error that occurred during parameter encoding,
  78. /// if any.
  79. public func encode(_ urlRequest: URLRequestConvertible, with parameters: [String: Any]?) throws -> URLRequest {
  80. var urlRequest = urlRequest.urlRequest
  81. guard let parameters = parameters else { return urlRequest }
  82. switch self {
  83. case .url, .urlEncodedInURL:
  84. func query(_ parameters: [String: Any]) -> String {
  85. var components: [(String, String)] = []
  86. for key in parameters.keys.sorted(by: <) {
  87. let value = parameters[key]!
  88. components += queryComponents(fromKey: key, value: value)
  89. }
  90. return components.map { "\($0)=\($1)" }.joined(separator: "&")
  91. }
  92. func encodesParametersInURL(with method: HTTPMethod) -> Bool {
  93. switch self {
  94. case .urlEncodedInURL:
  95. return true
  96. default:
  97. break
  98. }
  99. switch method {
  100. case .get, .head, .delete:
  101. return true
  102. default:
  103. return false
  104. }
  105. }
  106. if let method = HTTPMethod(rawValue: urlRequest.httpMethod!), encodesParametersInURL(with: method) {
  107. if
  108. var URLComponents = URLComponents(url: urlRequest.url!, resolvingAgainstBaseURL: false),
  109. !parameters.isEmpty
  110. {
  111. let percentEncodedQuery = (URLComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters)
  112. URLComponents.percentEncodedQuery = percentEncodedQuery
  113. urlRequest.url = URLComponents.url
  114. }
  115. } else {
  116. if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
  117. urlRequest.setValue(
  118. "application/x-www-form-urlencoded; charset=utf-8",
  119. forHTTPHeaderField: "Content-Type"
  120. )
  121. }
  122. urlRequest.httpBody = query(parameters).data(
  123. using: String.Encoding.utf8,
  124. allowLossyConversion: false
  125. )
  126. }
  127. case .json:
  128. do {
  129. let data = try JSONSerialization.data(withJSONObject: parameters, options: [])
  130. if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
  131. urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
  132. }
  133. urlRequest.httpBody = data
  134. } catch {
  135. throw AFError.parameterEncodingFailed(reason: .jsonSerializationFailed(error: error))
  136. }
  137. case .propertyList(let format, let options):
  138. do {
  139. let data = try PropertyListSerialization.data(
  140. fromPropertyList: parameters,
  141. format: format,
  142. options: options
  143. )
  144. if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
  145. urlRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
  146. }
  147. urlRequest.httpBody = data
  148. } catch {
  149. throw AFError.parameterEncodingFailed(reason: .propertyListSerializationFailed(error: error))
  150. }
  151. case .custom(let closure):
  152. urlRequest = try closure(urlRequest, parameters)
  153. }
  154. return urlRequest
  155. }
  156. /// Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion.
  157. ///
  158. /// - parameter key: The key of the query component.
  159. /// - parameter value: The value of the query component.
  160. ///
  161. /// - returns: The percent-escaped, URL encoded query string components.
  162. public func queryComponents(fromKey key: String, value: Any) -> [(String, String)] {
  163. var components: [(String, String)] = []
  164. if let dictionary = value as? [String: Any] {
  165. for (nestedKey, value) in dictionary {
  166. components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value)
  167. }
  168. } else if let array = value as? [Any] {
  169. for value in array {
  170. components += queryComponents(fromKey: "\(key)[]", value: value)
  171. }
  172. } else if let bool = value as? Bool {
  173. components.append((escape(key), escape((bool ? "1" : "0"))))
  174. } else {
  175. components.append((escape(key), escape("\(value)")))
  176. }
  177. return components
  178. }
  179. /// Returns a percent-escaped string following RFC 3986 for a query string key or value.
  180. ///
  181. /// RFC 3986 states that the following characters are "reserved" characters.
  182. ///
  183. /// - General Delimiters: ":", "#", "[", "]", "@", "?", "/"
  184. /// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
  185. ///
  186. /// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
  187. /// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
  188. /// should be percent-escaped in the query string.
  189. ///
  190. /// - parameter string: The string to be percent-escaped.
  191. ///
  192. /// - returns: The percent-escaped string.
  193. public func escape(_ string: String) -> String {
  194. let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
  195. let subDelimitersToEncode = "!$&'()*+,;="
  196. var allowedCharacterSet = CharacterSet.urlQueryAllowed
  197. allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
  198. return string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? string
  199. }
  200. }