信贷产品

AFURLRequestSerialization.h 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. // AFURLRequestSerialization.h
  2. // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. #import <Foundation/Foundation.h>
  22. #import <TargetConditionals.h>
  23. #if TARGET_OS_IOS || TARGET_OS_TV
  24. #import <UIKit/UIKit.h>
  25. #elif TARGET_OS_WATCH
  26. #import <WatchKit/WatchKit.h>
  27. #endif
  28. NS_ASSUME_NONNULL_BEGIN
  29. /**
  30. Returns a percent-escaped string following RFC 3986 for a query string key or value.
  31. RFC 3986 states that the following characters are "reserved" characters.
  32. - General Delimiters: ":", "#", "[", "]", "@", "?", "/"
  33. - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
  34. In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
  35. query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
  36. should be percent-escaped in the query string.
  37. @param string The string to be percent-escaped.
  38. @return The percent-escaped string.
  39. */
  40. FOUNDATION_EXPORT NSString * AFPercentEscapedStringFromString(NSString *string);
  41. /**
  42. A helper method to generate encoded url query parameters for appending to the end of a URL.
  43. @param parameters A dictionary of key/values to be encoded.
  44. @return A url encoded query string
  45. */
  46. FOUNDATION_EXPORT NSString * AFQueryStringFromParameters(NSDictionary *parameters);
  47. /**
  48. The `AFURLRequestSerialization` protocol is adopted by an object that encodes parameters for a specified HTTP requests. Request serializers may encode parameters as query strings, HTTP bodies, setting the appropriate HTTP header fields as necessary.
  49. For example, a JSON request serializer may set the HTTP body of the request to a JSON representation, and set the `Content-Type` HTTP header field value to `application/json`.
  50. */
  51. @protocol AFURLRequestSerialization <NSObject, NSSecureCoding, NSCopying>
  52. /**
  53. Returns a request with the specified parameters encoded into a copy of the original request.
  54. @param request The original request.
  55. @param parameters The parameters to be encoded.
  56. @param error The error that occurred while attempting to encode the request parameters.
  57. @return A serialized request.
  58. */
  59. - (nullable NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
  60. withParameters:(nullable id)parameters
  61. error:(NSError * _Nullable __autoreleasing *)error NS_SWIFT_NOTHROW;
  62. @end
  63. #pragma mark -
  64. /**
  65. */
  66. typedef NS_ENUM(NSUInteger, AFHTTPRequestQueryStringSerializationStyle) {
  67. AFHTTPRequestQueryStringDefaultStyle = 0,
  68. };
  69. @protocol AFMultipartFormData;
  70. /**
  71. `AFHTTPRequestSerializer` conforms to the `AFURLRequestSerialization` & `AFURLResponseSerialization` protocols, offering a concrete base implementation of query string / URL form-encoded parameter serialization and default request headers, as well as response status code and content type validation.
  72. Any request or response serializer dealing with HTTP is encouraged to subclass `AFHTTPRequestSerializer` in order to ensure consistent default behavior.
  73. */
  74. @interface AFHTTPRequestSerializer : NSObject <AFURLRequestSerialization>
  75. /**
  76. The string encoding used to serialize parameters. `NSUTF8StringEncoding` by default.
  77. */
  78. @property (nonatomic, assign) NSStringEncoding stringEncoding;
  79. /**
  80. Whether created requests can use the device’s cellular radio (if present). `YES` by default.
  81. @see NSMutableURLRequest -setAllowsCellularAccess:
  82. */
  83. @property (nonatomic, assign) BOOL allowsCellularAccess;
  84. /**
  85. The cache policy of created requests. `NSURLRequestUseProtocolCachePolicy` by default.
  86. @see NSMutableURLRequest -setCachePolicy:
  87. */
  88. @property (nonatomic, assign) NSURLRequestCachePolicy cachePolicy;
  89. /**
  90. Whether created requests should use the default cookie handling. `YES` by default.
  91. @see NSMutableURLRequest -setHTTPShouldHandleCookies:
  92. */
  93. @property (nonatomic, assign) BOOL HTTPShouldHandleCookies;
  94. /**
  95. Whether created requests can continue transmitting data before receiving a response from an earlier transmission. `NO` by default
  96. @see NSMutableURLRequest -setHTTPShouldUsePipelining:
  97. */
  98. @property (nonatomic, assign) BOOL HTTPShouldUsePipelining;
  99. /**
  100. The network service type for created requests. `NSURLNetworkServiceTypeDefault` by default.
  101. @see NSMutableURLRequest -setNetworkServiceType:
  102. */
  103. @property (nonatomic, assign) NSURLRequestNetworkServiceType networkServiceType;
  104. /**
  105. The timeout interval, in seconds, for created requests. The default timeout interval is 60 seconds.
  106. @see NSMutableURLRequest -setTimeoutInterval:
  107. */
  108. @property (nonatomic, assign) NSTimeInterval timeoutInterval;
  109. ///---------------------------------------
  110. /// @name Configuring HTTP Request Headers
  111. ///---------------------------------------
  112. /**
  113. Default HTTP header field values to be applied to serialized requests. By default, these include the following:
  114. - `Accept-Language` with the contents of `NSLocale +preferredLanguages`
  115. - `User-Agent` with the contents of various bundle identifiers and OS designations
  116. @discussion To add or remove default request headers, use `setValue:forHTTPHeaderField:`.
  117. */
  118. @property (readonly, nonatomic, strong) NSDictionary <NSString *, NSString *> *HTTPRequestHeaders;
  119. /**
  120. Creates and returns a serializer with default configuration.
  121. */
  122. + (instancetype)serializer;
  123. /**
  124. Sets the value for the HTTP headers set in request objects made by the HTTP client. If `nil`, removes the existing value for that header.
  125. @param field The HTTP header to set a default value for
  126. @param value The value set as default for the specified header, or `nil`
  127. */
  128. - (void)setValue:(nullable NSString *)value
  129. forHTTPHeaderField:(NSString *)field;
  130. /**
  131. Returns the value for the HTTP headers set in the request serializer.
  132. @param field The HTTP header to retrieve the default value for
  133. @return The value set as default for the specified header, or `nil`
  134. */
  135. - (nullable NSString *)valueForHTTPHeaderField:(NSString *)field;
  136. /**
  137. Sets the "Authorization" HTTP header set in request objects made by the HTTP client to a basic authentication value with Base64-encoded username and password. This overwrites any existing value for this header.
  138. @param username The HTTP basic auth username
  139. @param password The HTTP basic auth password
  140. */
  141. - (void)setAuthorizationHeaderFieldWithUsername:(NSString *)username
  142. password:(NSString *)password;
  143. /**
  144. Clears any existing value for the "Authorization" HTTP header.
  145. */
  146. - (void)clearAuthorizationHeader;
  147. ///-------------------------------------------------------
  148. /// @name Configuring Query String Parameter Serialization
  149. ///-------------------------------------------------------
  150. /**
  151. HTTP methods for which serialized requests will encode parameters as a query string. `GET`, `HEAD`, and `DELETE` by default.
  152. */
  153. @property (nonatomic, strong) NSSet <NSString *> *HTTPMethodsEncodingParametersInURI;
  154. /**
  155. Set the method of query string serialization according to one of the pre-defined styles.
  156. @param style The serialization style.
  157. @see AFHTTPRequestQueryStringSerializationStyle
  158. */
  159. - (void)setQueryStringSerializationWithStyle:(AFHTTPRequestQueryStringSerializationStyle)style;
  160. /**
  161. Set the a custom method of query string serialization according to the specified block.
  162. @param block A block that defines a process of encoding parameters into a query string. This block returns the query string and takes three arguments: the request, the parameters to encode, and the error that occurred when attempting to encode parameters for the given request.
  163. */
  164. - (void)setQueryStringSerializationWithBlock:(nullable NSString * (^)(NSURLRequest *request, id parameters, NSError * __autoreleasing *error))block;
  165. ///-------------------------------
  166. /// @name Creating Request Objects
  167. ///-------------------------------
  168. /**
  169. Creates an `NSMutableURLRequest` object with the specified HTTP method and URL string.
  170. If the HTTP method is `GET`, `HEAD`, or `DELETE`, the parameters will be used to construct a url-encoded query string that is appended to the request's URL. Otherwise, the parameters will be encoded according to the value of the `parameterEncoding` property, and set as the request body.
  171. @param method The HTTP method for the request, such as `GET`, `POST`, `PUT`, or `DELETE`. This parameter must not be `nil`.
  172. @param URLString The URL string used to create the request URL.
  173. @param parameters The parameters to be either set as a query string for `GET` requests, or the request HTTP body.
  174. @param error The error that occurred while constructing the request.
  175. @return An `NSMutableURLRequest` object.
  176. */
  177. - (NSMutableURLRequest *)requestWithMethod:(NSString *)method
  178. URLString:(NSString *)URLString
  179. parameters:(nullable id)parameters
  180. error:(NSError * _Nullable __autoreleasing *)error;
  181. /**
  182. Creates an `NSMutableURLRequest` object with the specified HTTP method and URLString, and constructs a `multipart/form-data` HTTP body, using the specified parameters and multipart form data block. See http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.2
  183. Multipart form requests are automatically streamed, reading files directly from disk along with in-memory data in a single HTTP body. The resulting `NSMutableURLRequest` object has an `HTTPBodyStream` property, so refrain from setting `HTTPBodyStream` or `HTTPBody` on this request object, as it will clear out the multipart form body stream.
  184. @param method The HTTP method for the request. This parameter must not be `GET` or `HEAD`, or `nil`.
  185. @param URLString The URL string used to create the request URL.
  186. @param parameters The parameters to be encoded and set in the request HTTP body.
  187. @param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol.
  188. @param error The error that occurred while constructing the request.
  189. @return An `NSMutableURLRequest` object
  190. */
  191. - (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
  192. URLString:(NSString *)URLString
  193. parameters:(nullable NSDictionary <NSString *, id> *)parameters
  194. constructingBodyWithBlock:(nullable void (^)(id <AFMultipartFormData> formData))block
  195. error:(NSError * _Nullable __autoreleasing *)error;
  196. /**
  197. Creates an `NSMutableURLRequest` by removing the `HTTPBodyStream` from a request, and asynchronously writing its contents into the specified file, invoking the completion handler when finished.
  198. @param request The multipart form request. The `HTTPBodyStream` property of `request` must not be `nil`.
  199. @param fileURL The file URL to write multipart form contents to.
  200. @param handler A handler block to execute.
  201. @discussion There is a bug in `NSURLSessionTask` that causes requests to not send a `Content-Length` header when streaming contents from an HTTP body, which is notably problematic when interacting with the Amazon S3 webservice. As a workaround, this method takes a request constructed with `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:error:`, or any other request with an `HTTPBodyStream`, writes the contents to the specified file and returns a copy of the original request with the `HTTPBodyStream` property set to `nil`. From here, the file can either be passed to `AFURLSessionManager -uploadTaskWithRequest:fromFile:progress:completionHandler:`, or have its contents read into an `NSData` that's assigned to the `HTTPBody` property of the request.
  202. @see https://github.com/AFNetworking/AFNetworking/issues/1398
  203. */
  204. - (NSMutableURLRequest *)requestWithMultipartFormRequest:(NSURLRequest *)request
  205. writingStreamContentsToFile:(NSURL *)fileURL
  206. completionHandler:(nullable void (^)(NSError * _Nullable error))handler;
  207. @end
  208. #pragma mark -
  209. /**
  210. The `AFMultipartFormData` protocol defines the methods supported by the parameter in the block argument of `AFHTTPRequestSerializer -multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:`.
  211. */
  212. @protocol AFMultipartFormData
  213. /**
  214. Appends the HTTP header `Content-Disposition: file; filename=#{generated filename}; name=#{name}"` and `Content-Type: #{generated mimeType}`, followed by the encoded file data and the multipart form boundary.
  215. The filename and MIME type for this data in the form will be automatically generated, using the last path component of the `fileURL` and system associated MIME type for the `fileURL` extension, respectively.
  216. @param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`.
  217. @param name The name to be associated with the specified data. This parameter must not be `nil`.
  218. @param error If an error occurs, upon return contains an `NSError` object that describes the problem.
  219. @return `YES` if the file data was successfully appended, otherwise `NO`.
  220. */
  221. - (BOOL)appendPartWithFileURL:(NSURL *)fileURL
  222. name:(NSString *)name
  223. error:(NSError * _Nullable __autoreleasing *)error;
  224. /**
  225. Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the encoded file data and the multipart form boundary.
  226. @param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`.
  227. @param name The name to be associated with the specified data. This parameter must not be `nil`.
  228. @param fileName The file name to be used in the `Content-Disposition` header. This parameter must not be `nil`.
  229. @param mimeType The declared MIME type of the file data. This parameter must not be `nil`.
  230. @param error If an error occurs, upon return contains an `NSError` object that describes the problem.
  231. @return `YES` if the file data was successfully appended otherwise `NO`.
  232. */
  233. - (BOOL)appendPartWithFileURL:(NSURL *)fileURL
  234. name:(NSString *)name
  235. fileName:(NSString *)fileName
  236. mimeType:(NSString *)mimeType
  237. error:(NSError * _Nullable __autoreleasing *)error;
  238. /**
  239. Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the data from the input stream and the multipart form boundary.
  240. @param inputStream The input stream to be appended to the form data
  241. @param name The name to be associated with the specified input stream. This parameter must not be `nil`.
  242. @param fileName The filename to be associated with the specified input stream. This parameter must not be `nil`.
  243. @param length The length of the specified input stream in bytes.
  244. @param mimeType The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be `nil`.
  245. */
  246. - (void)appendPartWithInputStream:(nullable NSInputStream *)inputStream
  247. name:(NSString *)name
  248. fileName:(NSString *)fileName
  249. length:(int64_t)length
  250. mimeType:(NSString *)mimeType;
  251. /**
  252. Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the encoded file data and the multipart form boundary.
  253. @param data The data to be encoded and appended to the form data.
  254. @param name The name to be associated with the specified data. This parameter must not be `nil`.
  255. @param fileName The filename to be associated with the specified data. This parameter must not be `nil`.
  256. @param mimeType The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be `nil`.
  257. */
  258. - (void)appendPartWithFileData:(NSData *)data
  259. name:(NSString *)name
  260. fileName:(NSString *)fileName
  261. mimeType:(NSString *)mimeType;
  262. /**
  263. Appends the HTTP headers `Content-Disposition: form-data; name=#{name}"`, followed by the encoded data and the multipart form boundary.
  264. @param data The data to be encoded and appended to the form data.
  265. @param name The name to be associated with the specified data. This parameter must not be `nil`.
  266. */
  267. - (void)appendPartWithFormData:(NSData *)data
  268. name:(NSString *)name;
  269. /**
  270. Appends HTTP headers, followed by the encoded data and the multipart form boundary.
  271. @param headers The HTTP headers to be appended to the form data.
  272. @param body The data to be encoded and appended to the form data. This parameter must not be `nil`.
  273. */
  274. - (void)appendPartWithHeaders:(nullable NSDictionary <NSString *, NSString *> *)headers
  275. body:(NSData *)body;
  276. /**
  277. Throttles request bandwidth by limiting the packet size and adding a delay for each chunk read from the upload stream.
  278. When uploading over a 3G or EDGE connection, requests may fail with "request body stream exhausted". Setting a maximum packet size and delay according to the recommended values (`kAFUploadStream3GSuggestedPacketSize` and `kAFUploadStream3GSuggestedDelay`) lowers the risk of the input stream exceeding its allocated bandwidth. Unfortunately, there is no definite way to distinguish between a 3G, EDGE, or LTE connection over `NSURLConnection`. As such, it is not recommended that you throttle bandwidth based solely on network reachability. Instead, you should consider checking for the "request body stream exhausted" in a failure block, and then retrying the request with throttled bandwidth.
  279. @param numberOfBytes Maximum packet size, in number of bytes. The default packet size for an input stream is 16kb.
  280. @param delay Duration of delay each time a packet is read. By default, no delay is set.
  281. */
  282. - (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes
  283. delay:(NSTimeInterval)delay;
  284. @end
  285. #pragma mark -
  286. /**
  287. `AFJSONRequestSerializer` is a subclass of `AFHTTPRequestSerializer` that encodes parameters as JSON using `NSJSONSerialization`, setting the `Content-Type` of the encoded request to `application/json`.
  288. */
  289. @interface AFJSONRequestSerializer : AFHTTPRequestSerializer
  290. /**
  291. Options for writing the request JSON data from Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONWritingOptions". `0` by default.
  292. */
  293. @property (nonatomic, assign) NSJSONWritingOptions writingOptions;
  294. /**
  295. Creates and returns a JSON serializer with specified reading and writing options.
  296. @param writingOptions The specified JSON writing options.
  297. */
  298. + (instancetype)serializerWithWritingOptions:(NSJSONWritingOptions)writingOptions;
  299. @end
  300. #pragma mark -
  301. /**
  302. `AFPropertyListRequestSerializer` is a subclass of `AFHTTPRequestSerializer` that encodes parameters as JSON using `NSPropertyListSerializer`, setting the `Content-Type` of the encoded request to `application/x-plist`.
  303. */
  304. @interface AFPropertyListRequestSerializer : AFHTTPRequestSerializer
  305. /**
  306. The property list format. Possible values are described in "NSPropertyListFormat".
  307. */
  308. @property (nonatomic, assign) NSPropertyListFormat format;
  309. /**
  310. @warning The `writeOptions` property is currently unused.
  311. */
  312. @property (nonatomic, assign) NSPropertyListWriteOptions writeOptions;
  313. /**
  314. Creates and returns a property list serializer with a specified format, read options, and write options.
  315. @param format The property list format.
  316. @param writeOptions The property list write options.
  317. @warning The `writeOptions` property is currently unused.
  318. */
  319. + (instancetype)serializerWithFormat:(NSPropertyListFormat)format
  320. writeOptions:(NSPropertyListWriteOptions)writeOptions;
  321. @end
  322. #pragma mark -
  323. ///----------------
  324. /// @name Constants
  325. ///----------------
  326. /**
  327. ## Error Domains
  328. The following error domain is predefined.
  329. - `NSString * const AFURLRequestSerializationErrorDomain`
  330. ### Constants
  331. `AFURLRequestSerializationErrorDomain`
  332. AFURLRequestSerializer errors. Error codes for `AFURLRequestSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`.
  333. */
  334. FOUNDATION_EXPORT NSString * const AFURLRequestSerializationErrorDomain;
  335. /**
  336. ## User info dictionary keys
  337. These keys may exist in the user info dictionary, in addition to those defined for NSError.
  338. - `NSString * const AFNetworkingOperationFailingURLRequestErrorKey`
  339. ### Constants
  340. `AFNetworkingOperationFailingURLRequestErrorKey`
  341. The corresponding value is an `NSURLRequest` containing the request of the operation associated with an error. This key is only present in the `AFURLRequestSerializationErrorDomain`.
  342. */
  343. FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLRequestErrorKey;
  344. /**
  345. ## Throttling Bandwidth for HTTP Request Input Streams
  346. @see -throttleBandwidthWithPacketSize:delay:
  347. ### Constants
  348. `kAFUploadStream3GSuggestedPacketSize`
  349. Maximum packet size, in number of bytes. Equal to 16kb.
  350. `kAFUploadStream3GSuggestedDelay`
  351. Duration of delay each time a packet is read. Equal to 0.2 seconds.
  352. */
  353. FOUNDATION_EXPORT NSUInteger const kAFUploadStream3GSuggestedPacketSize;
  354. FOUNDATION_EXPORT NSTimeInterval const kAFUploadStream3GSuggestedDelay;
  355. NS_ASSUME_NONNULL_END