AFURLRequestSerialization.h 22 KB

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