ParameterEncoding.swift 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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]?) -> (URLRequest, Error?))
  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. /// - returns: A tuple containing the constructed request and the error that occurred during parameter encoding,
  76. /// if any.
  77. public func encode(
  78. _ urlRequest: URLRequestConvertible,
  79. parameters: [String: Any]?)
  80. -> (URLRequest, Error?)
  81. {
  82. var urlRequest = urlRequest.urlRequest
  83. guard let parameters = parameters else { return (urlRequest, nil) }
  84. var encodingError: Error? = nil
  85. switch self {
  86. case .url, .urlEncodedInURL:
  87. func query(_ parameters: [String: Any]) -> String {
  88. var components: [(String, String)] = []
  89. for key in parameters.keys.sorted(by: <) {
  90. let value = parameters[key]!
  91. components += queryComponents(fromKey: key, value: value)
  92. }
  93. return components.map { "\($0)=\($1)" }.joined(separator: "&")
  94. }
  95. func encodesParametersInURL(with method: HTTPMethod) -> Bool {
  96. switch self {
  97. case .urlEncodedInURL:
  98. return true
  99. default:
  100. break
  101. }
  102. switch method {
  103. case .get, .head, .delete:
  104. return true
  105. default:
  106. return false
  107. }
  108. }
  109. if let method = HTTPMethod(rawValue: urlRequest.httpMethod!), encodesParametersInURL(with: method) {
  110. if
  111. var URLComponents = URLComponents(url: urlRequest.url!, resolvingAgainstBaseURL: false),
  112. !parameters.isEmpty
  113. {
  114. let percentEncodedQuery = (URLComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters)
  115. URLComponents.percentEncodedQuery = percentEncodedQuery
  116. urlRequest.url = URLComponents.url
  117. }
  118. } else {
  119. if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
  120. urlRequest.setValue(
  121. "application/x-www-form-urlencoded; charset=utf-8",
  122. forHTTPHeaderField: "Content-Type"
  123. )
  124. }
  125. urlRequest.httpBody = query(parameters).data(
  126. using: String.Encoding.utf8,
  127. allowLossyConversion: false
  128. )
  129. }
  130. case .json:
  131. do {
  132. let data = try JSONSerialization.data(withJSONObject: parameters, options: [])
  133. if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
  134. urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
  135. }
  136. urlRequest.httpBody = data
  137. } catch {
  138. encodingError = error
  139. }
  140. case .propertyList(let format, let options):
  141. do {
  142. let data = try PropertyListSerialization.data(
  143. fromPropertyList: parameters,
  144. format: format,
  145. options: options
  146. )
  147. if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
  148. urlRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
  149. }
  150. urlRequest.httpBody = data
  151. } catch {
  152. encodingError = error
  153. }
  154. case .custom(let closure):
  155. (urlRequest, encodingError) = closure(urlRequest, parameters)
  156. }
  157. return (urlRequest, encodingError)
  158. }
  159. /// Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion.
  160. ///
  161. /// - parameter key: The key of the query component.
  162. /// - parameter value: The value of the query component.
  163. ///
  164. /// - returns: The percent-escaped, URL encoded query string components.
  165. public func queryComponents(fromKey key: String, value: Any) -> [(String, String)] {
  166. var components: [(String, String)] = []
  167. if let dictionary = value as? [String: Any] {
  168. for (nestedKey, value) in dictionary {
  169. components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value)
  170. }
  171. } else if let array = value as? [Any] {
  172. for value in array {
  173. components += queryComponents(fromKey: "\(key)[]", value: value)
  174. }
  175. } else if let bool = value as? Bool {
  176. components.append((escape(key), escape((bool ? "1" : "0"))))
  177. } else {
  178. components.append((escape(key), escape("\(value)")))
  179. }
  180. return components
  181. }
  182. /// Returns a percent-escaped string following RFC 3986 for a query string key or value.
  183. ///
  184. /// RFC 3986 states that the following characters are "reserved" characters.
  185. ///
  186. /// - General Delimiters: ":", "#", "[", "]", "@", "?", "/"
  187. /// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
  188. ///
  189. /// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
  190. /// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
  191. /// should be percent-escaped in the query string.
  192. ///
  193. /// - parameter string: The string to be percent-escaped.
  194. ///
  195. /// - returns: The percent-escaped string.
  196. public func escape(_ string: String) -> String {
  197. let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
  198. let subDelimitersToEncode = "!$&'()*+,;="
  199. var allowedCharacterSet = CharacterSet.urlQueryAllowed
  200. allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
  201. return string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? string
  202. }
  203. }