PageRenderTime 24ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/Pods/Headers/Private/AFNetworking/AFURLRequestSerialization.h

https://gitlab.com/trungminhnt/sampleShinobi
C Header | 476 lines | 105 code | 64 blank | 307 comment | 0 complexity | e2b897c535d27963accbce92e14ae745 MD5 | raw file
  1. // AFURLRequestSerialization.h
  2. // Copyright (c) 2011–2015 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. #if TARGET_OS_IOS
  23. #import <UIKit/UIKit.h>
  24. #elif TARGET_OS_WATCH
  25. #import <WatchKit/WatchKit.h>
  26. #endif
  27. NS_ASSUME_NONNULL_BEGIN
  28. /**
  29. 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.
  30. 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`.
  31. */
  32. @protocol AFURLRequestSerialization <NSObject, NSSecureCoding, NSCopying>
  33. /**
  34. Returns a request with the specified parameters encoded into a copy of the original request.
  35. @param request The original request.
  36. @param parameters The parameters to be encoded.
  37. @param error The error that occurred while attempting to encode the request parameters.
  38. @return A serialized request.
  39. */
  40. - (nullable NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
  41. withParameters:(nullable id)parameters
  42. error:(NSError * __nullable __autoreleasing *)error
  43. #ifdef NS_SWIFT_NOTHROW
  44. NS_SWIFT_NOTHROW
  45. #endif
  46. ;
  47. @end
  48. #pragma mark -
  49. /**
  50. */
  51. typedef NS_ENUM(NSUInteger, AFHTTPRequestQueryStringSerializationStyle) {
  52. AFHTTPRequestQueryStringDefaultStyle = 0,
  53. };
  54. @protocol AFMultipartFormData;
  55. /**
  56. `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.
  57. Any request or response serializer dealing with HTTP is encouraged to subclass `AFHTTPRequestSerializer` in order to ensure consistent default behavior.
  58. */
  59. @interface AFHTTPRequestSerializer : NSObject <AFURLRequestSerialization>
  60. /**
  61. The string encoding used to serialize parameters. `NSUTF8StringEncoding` by default.
  62. */
  63. @property (nonatomic, assign) NSStringEncoding stringEncoding;
  64. /**
  65. Whether created requests can use the device’s cellular radio (if present). `YES` by default.
  66. @see NSMutableURLRequest -setAllowsCellularAccess:
  67. */
  68. @property (nonatomic, assign) BOOL allowsCellularAccess;
  69. /**
  70. The cache policy of created requests. `NSURLRequestUseProtocolCachePolicy` by default.
  71. @see NSMutableURLRequest -setCachePolicy:
  72. */
  73. @property (nonatomic, assign) NSURLRequestCachePolicy cachePolicy;
  74. /**
  75. Whether created requests should use the default cookie handling. `YES` by default.
  76. @see NSMutableURLRequest -setHTTPShouldHandleCookies:
  77. */
  78. @property (nonatomic, assign) BOOL HTTPShouldHandleCookies;
  79. /**
  80. Whether created requests can continue transmitting data before receiving a response from an earlier transmission. `NO` by default
  81. @see NSMutableURLRequest -setHTTPShouldUsePipelining:
  82. */
  83. @property (nonatomic, assign) BOOL HTTPShouldUsePipelining;
  84. /**
  85. The network service type for created requests. `NSURLNetworkServiceTypeDefault` by default.
  86. @see NSMutableURLRequest -setNetworkServiceType:
  87. */
  88. @property (nonatomic, assign) NSURLRequestNetworkServiceType networkServiceType;
  89. /**
  90. The timeout interval, in seconds, for created requests. The default timeout interval is 60 seconds.
  91. @see NSMutableURLRequest -setTimeoutInterval:
  92. */
  93. @property (nonatomic, assign) NSTimeInterval timeoutInterval;
  94. ///---------------------------------------
  95. /// @name Configuring HTTP Request Headers
  96. ///---------------------------------------
  97. /**
  98. Default HTTP header field values to be applied to serialized requests. By default, these include the following:
  99. - `Accept-Language` with the contents of `NSLocale +preferredLanguages`
  100. - `User-Agent` with the contents of various bundle identifiers and OS designations
  101. @discussion To add or remove default request headers, use `setValue:forHTTPHeaderField:`.
  102. */
  103. @property (readonly, nonatomic, strong) NSDictionary *HTTPRequestHeaders;
  104. /**
  105. Creates and returns a serializer with default configuration.
  106. */
  107. + (instancetype)serializer;
  108. /**
  109. 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.
  110. @param field The HTTP header to set a default value for
  111. @param value The value set as default for the specified header, or `nil`
  112. */
  113. - (void)setValue:(nullable NSString *)value
  114. forHTTPHeaderField:(NSString *)field;
  115. /**
  116. Returns the value for the HTTP headers set in the request serializer.
  117. @param field The HTTP header to retrieve the default value for
  118. @return The value set as default for the specified header, or `nil`
  119. */
  120. - (nullable NSString *)valueForHTTPHeaderField:(NSString *)field;
  121. /**
  122. 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.
  123. @param username The HTTP basic auth username
  124. @param password The HTTP basic auth password
  125. */
  126. - (void)setAuthorizationHeaderFieldWithUsername:(NSString *)username
  127. password:(NSString *)password;
  128. /**
  129. @deprecated This method has been deprecated. Use -setValue:forHTTPHeaderField: instead.
  130. */
  131. - (void)setAuthorizationHeaderFieldWithToken:(NSString *)token DEPRECATED_ATTRIBUTE;
  132. /**
  133. Clears any existing value for the "Authorization" HTTP header.
  134. */
  135. - (void)clearAuthorizationHeader;
  136. ///-------------------------------------------------------
  137. /// @name Configuring Query String Parameter Serialization
  138. ///-------------------------------------------------------
  139. /**
  140. HTTP methods for which serialized requests will encode parameters as a query string. `GET`, `HEAD`, and `DELETE` by default.
  141. */
  142. @property (nonatomic, strong) NSSet *HTTPMethodsEncodingParametersInURI;
  143. /**
  144. Set the method of query string serialization according to one of the pre-defined styles.
  145. @param style The serialization style.
  146. @see AFHTTPRequestQueryStringSerializationStyle
  147. */
  148. - (void)setQueryStringSerializationWithStyle:(AFHTTPRequestQueryStringSerializationStyle)style;
  149. /**
  150. Set the a custom method of query string serialization according to the specified block.
  151. @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.
  152. */
  153. - (void)setQueryStringSerializationWithBlock:(nullable NSString * (^)(NSURLRequest *request, id parameters, NSError * __autoreleasing *error))block;
  154. ///-------------------------------
  155. /// @name Creating Request Objects
  156. ///-------------------------------
  157. /**
  158. @deprecated This method has been deprecated. Use -requestWithMethod:URLString:parameters:error: instead.
  159. */
  160. - (NSMutableURLRequest *)requestWithMethod:(NSString *)method
  161. URLString:(NSString *)URLString
  162. parameters:(id)parameters DEPRECATED_ATTRIBUTE;
  163. /**
  164. Creates an `NSMutableURLRequest` object with the specified HTTP method and URL string.
  165. 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.
  166. @param method The HTTP method for the request, such as `GET`, `POST`, `PUT`, or `DELETE`. This parameter must not be `nil`.
  167. @param URLString The URL string used to create the request URL.
  168. @param parameters The parameters to be either set as a query string for `GET` requests, or the request HTTP body.
  169. @param error The error that occurred while constructing the request.
  170. @return An `NSMutableURLRequest` object.
  171. */
  172. - (NSMutableURLRequest *)requestWithMethod:(NSString *)method
  173. URLString:(NSString *)URLString
  174. parameters:(nullable id)parameters
  175. error:(NSError * __nullable __autoreleasing *)error;
  176. /**
  177. @deprecated This method has been deprecated. Use -multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:error: instead.
  178. */
  179. - (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
  180. URLString:(NSString *)URLString
  181. parameters:(NSDictionary *)parameters
  182. constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block DEPRECATED_ATTRIBUTE;
  183. /**
  184. 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
  185. 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.
  186. @param method The HTTP method for the request. This parameter must not be `GET` or `HEAD`, or `nil`.
  187. @param URLString The URL string used to create the request URL.
  188. @param parameters The parameters to be encoded and set in the request HTTP body.
  189. @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.
  190. @param error The error that occurred while constructing the request.
  191. @return An `NSMutableURLRequest` object
  192. */
  193. - (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
  194. URLString:(NSString *)URLString
  195. parameters:(nullable NSDictionary *)parameters
  196. constructingBodyWithBlock:(nullable void (^)(id <AFMultipartFormData> formData))block
  197. error:(NSError * __nullable __autoreleasing *)error;
  198. /**
  199. 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.
  200. @param request The multipart form request. The `HTTPBodyStream` property of `request` must not be `nil`.
  201. @param fileURL The file URL to write multipart form contents to.
  202. @param handler A handler block to execute.
  203. @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.
  204. @see https://github.com/AFNetworking/AFNetworking/issues/1398
  205. */
  206. - (NSMutableURLRequest *)requestWithMultipartFormRequest:(NSURLRequest *)request
  207. writingStreamContentsToFile:(NSURL *)fileURL
  208. completionHandler:(nullable void (^)(NSError * __nullable error))handler;
  209. @end
  210. #pragma mark -
  211. /**
  212. The `AFMultipartFormData` protocol defines the methods supported by the parameter in the block argument of `AFHTTPRequestSerializer -multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:`.
  213. */
  214. @protocol AFMultipartFormData
  215. /**
  216. 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.
  217. 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.
  218. @param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`.
  219. @param name The name to be associated with the specified data. This parameter must not be `nil`.
  220. @param error If an error occurs, upon return contains an `NSError` object that describes the problem.
  221. @return `YES` if the file data was successfully appended, otherwise `NO`.
  222. */
  223. - (BOOL)appendPartWithFileURL:(NSURL *)fileURL
  224. name:(NSString *)name
  225. error:(NSError * __nullable __autoreleasing *)error;
  226. /**
  227. 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.
  228. @param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`.
  229. @param name The name to be associated with the specified data. This parameter must not be `nil`.
  230. @param fileName The file name to be used in the `Content-Disposition` header. This parameter must not be `nil`.
  231. @param mimeType The declared MIME type of the file data. This parameter must not be `nil`.
  232. @param error If an error occurs, upon return contains an `NSError` object that describes the problem.
  233. @return `YES` if the file data was successfully appended otherwise `NO`.
  234. */
  235. - (BOOL)appendPartWithFileURL:(NSURL *)fileURL
  236. name:(NSString *)name
  237. fileName:(NSString *)fileName
  238. mimeType:(NSString *)mimeType
  239. error:(NSError * __nullable __autoreleasing *)error;
  240. /**
  241. 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.
  242. @param inputStream The input stream to be appended to the form data
  243. @param name The name to be associated with the specified input stream. This parameter must not be `nil`.
  244. @param fileName The filename to be associated with the specified input stream. This parameter must not be `nil`.
  245. @param length The length of the specified input stream in bytes.
  246. @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`.
  247. */
  248. - (void)appendPartWithInputStream:(nullable NSInputStream *)inputStream
  249. name:(NSString *)name
  250. fileName:(NSString *)fileName
  251. length:(int64_t)length
  252. mimeType:(NSString *)mimeType;
  253. /**
  254. 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.
  255. @param data The data to be encoded and appended to the form data.
  256. @param name The name to be associated with the specified data. This parameter must not be `nil`.
  257. @param fileName The filename to be associated with the specified data. This parameter must not be `nil`.
  258. @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`.
  259. */
  260. - (void)appendPartWithFileData:(NSData *)data
  261. name:(NSString *)name
  262. fileName:(NSString *)fileName
  263. mimeType:(NSString *)mimeType;
  264. /**
  265. Appends the HTTP headers `Content-Disposition: form-data; name=#{name}"`, followed by the encoded data and the multipart form boundary.
  266. @param data The data to be encoded and appended to the form data.
  267. @param name The name to be associated with the specified data. This parameter must not be `nil`.
  268. */
  269. - (void)appendPartWithFormData:(NSData *)data
  270. name:(NSString *)name;
  271. /**
  272. Appends HTTP headers, followed by the encoded data and the multipart form boundary.
  273. @param headers The HTTP headers to be appended to the form data.
  274. @param body The data to be encoded and appended to the form data. This parameter must not be `nil`.
  275. */
  276. - (void)appendPartWithHeaders:(nullable NSDictionary *)headers
  277. body:(NSData *)body;
  278. /**
  279. Throttles request bandwidth by limiting the packet size and adding a delay for each chunk read from the upload stream.
  280. 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.
  281. @param numberOfBytes Maximum packet size, in number of bytes. The default packet size for an input stream is 16kb.
  282. @param delay Duration of delay each time a packet is read. By default, no delay is set.
  283. */
  284. - (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes
  285. delay:(NSTimeInterval)delay;
  286. @end
  287. #pragma mark -
  288. /**
  289. `AFJSONRequestSerializer` is a subclass of `AFHTTPRequestSerializer` that encodes parameters as JSON using `NSJSONSerialization`, setting the `Content-Type` of the encoded request to `application/json`.
  290. */
  291. @interface AFJSONRequestSerializer : AFHTTPRequestSerializer
  292. /**
  293. Options for writing the request JSON data from Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONWritingOptions". `0` by default.
  294. */
  295. @property (nonatomic, assign) NSJSONWritingOptions writingOptions;
  296. /**
  297. Creates and returns a JSON serializer with specified reading and writing options.
  298. @param writingOptions The specified JSON writing options.
  299. */
  300. + (instancetype)serializerWithWritingOptions:(NSJSONWritingOptions)writingOptions;
  301. @end
  302. #pragma mark -
  303. /**
  304. `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`.
  305. */
  306. @interface AFPropertyListRequestSerializer : AFHTTPRequestSerializer
  307. /**
  308. The property list format. Possible values are described in "NSPropertyListFormat".
  309. */
  310. @property (nonatomic, assign) NSPropertyListFormat format;
  311. /**
  312. @warning The `writeOptions` property is currently unused.
  313. */
  314. @property (nonatomic, assign) NSPropertyListWriteOptions writeOptions;
  315. /**
  316. Creates and returns a property list serializer with a specified format, read options, and write options.
  317. @param format The property list format.
  318. @param writeOptions The property list write options.
  319. @warning The `writeOptions` property is currently unused.
  320. */
  321. + (instancetype)serializerWithFormat:(NSPropertyListFormat)format
  322. writeOptions:(NSPropertyListWriteOptions)writeOptions;
  323. @end
  324. #pragma mark -
  325. ///----------------
  326. /// @name Constants
  327. ///----------------
  328. /**
  329. ## Error Domains
  330. The following error domain is predefined.
  331. - `NSString * const AFURLRequestSerializationErrorDomain`
  332. ### Constants
  333. `AFURLRequestSerializationErrorDomain`
  334. AFURLRequestSerializer errors. Error codes for `AFURLRequestSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`.
  335. */
  336. FOUNDATION_EXPORT NSString * const AFURLRequestSerializationErrorDomain;
  337. /**
  338. ## User info dictionary keys
  339. These keys may exist in the user info dictionary, in addition to those defined for NSError.
  340. - `NSString * const AFNetworkingOperationFailingURLRequestErrorKey`
  341. ### Constants
  342. `AFNetworkingOperationFailingURLRequestErrorKey`
  343. The corresponding value is an `NSURLRequest` containing the request of the operation associated with an error. This key is only present in the `AFURLRequestSerializationErrorDomain`.
  344. */
  345. FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLRequestErrorKey;
  346. /**
  347. ## Throttling Bandwidth for HTTP Request Input Streams
  348. @see -throttleBandwidthWithPacketSize:delay:
  349. ### Constants
  350. `kAFUploadStream3GSuggestedPacketSize`
  351. Maximum packet size, in number of bytes. Equal to 16kb.
  352. `kAFUploadStream3GSuggestedDelay`
  353. Duration of delay each time a packet is read. Equal to 0.2 seconds.
  354. */
  355. FOUNDATION_EXPORT NSUInteger const kAFUploadStream3GSuggestedPacketSize;
  356. FOUNDATION_EXPORT NSTimeInterval const kAFUploadStream3GSuggestedDelay;
  357. NS_ASSUME_NONNULL_END