信贷产品

AFHTTPSessionManager.m 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. // AFHTTPSessionManager.m
  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 "AFHTTPSessionManager.h"
  22. #import "AFURLRequestSerialization.h"
  23. #import "AFURLResponseSerialization.h"
  24. #import <Availability.h>
  25. #import <TargetConditionals.h>
  26. #import <Security/Security.h>
  27. #import <netinet/in.h>
  28. #import <netinet6/in6.h>
  29. #import <arpa/inet.h>
  30. #import <ifaddrs.h>
  31. #import <netdb.h>
  32. #if TARGET_OS_IOS || TARGET_OS_TV
  33. #import <UIKit/UIKit.h>
  34. #elif TARGET_OS_WATCH
  35. #import <WatchKit/WatchKit.h>
  36. #endif
  37. @interface AFHTTPSessionManager ()
  38. @property (readwrite, nonatomic, strong) NSURL *baseURL;
  39. @end
  40. @implementation AFHTTPSessionManager
  41. @dynamic responseSerializer;
  42. + (instancetype)manager {
  43. return [[[self class] alloc] initWithBaseURL:nil];
  44. }
  45. - (instancetype)init {
  46. return [self initWithBaseURL:nil];
  47. }
  48. - (instancetype)initWithBaseURL:(NSURL *)url {
  49. return [self initWithBaseURL:url sessionConfiguration:nil];
  50. }
  51. - (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration {
  52. return [self initWithBaseURL:nil sessionConfiguration:configuration];
  53. }
  54. - (instancetype)initWithBaseURL:(NSURL *)url
  55. sessionConfiguration:(NSURLSessionConfiguration *)configuration
  56. {
  57. self = [super initWithSessionConfiguration:configuration];
  58. if (!self) {
  59. return nil;
  60. }
  61. // Ensure terminal slash for baseURL path, so that NSURL +URLWithString:relativeToURL: works as expected
  62. if ([[url path] length] > 0 && ![[url absoluteString] hasSuffix:@"/"]) {
  63. url = [url URLByAppendingPathComponent:@""];
  64. }
  65. self.baseURL = url;
  66. self.requestSerializer = [AFHTTPRequestSerializer serializer];
  67. self.responseSerializer = [AFJSONResponseSerializer serializer];
  68. return self;
  69. }
  70. #pragma mark -
  71. - (void)setRequestSerializer:(AFHTTPRequestSerializer <AFURLRequestSerialization> *)requestSerializer {
  72. NSParameterAssert(requestSerializer);
  73. _requestSerializer = requestSerializer;
  74. }
  75. - (void)setResponseSerializer:(AFHTTPResponseSerializer <AFURLResponseSerialization> *)responseSerializer {
  76. NSParameterAssert(responseSerializer);
  77. [super setResponseSerializer:responseSerializer];
  78. }
  79. @dynamic securityPolicy;
  80. - (void)setSecurityPolicy:(AFSecurityPolicy *)securityPolicy {
  81. if (securityPolicy.SSLPinningMode != AFSSLPinningModeNone && ![self.baseURL.scheme isEqualToString:@"https"]) {
  82. NSString *pinningMode = @"Unknown Pinning Mode";
  83. switch (securityPolicy.SSLPinningMode) {
  84. case AFSSLPinningModeNone: pinningMode = @"AFSSLPinningModeNone"; break;
  85. case AFSSLPinningModeCertificate: pinningMode = @"AFSSLPinningModeCertificate"; break;
  86. case AFSSLPinningModePublicKey: pinningMode = @"AFSSLPinningModePublicKey"; break;
  87. }
  88. NSString *reason = [NSString stringWithFormat:@"A security policy configured with `%@` can only be applied on a manager with a secure base URL (i.e. https)", pinningMode];
  89. @throw [NSException exceptionWithName:@"Invalid Security Policy" reason:reason userInfo:nil];
  90. }
  91. [super setSecurityPolicy:securityPolicy];
  92. }
  93. #pragma mark -
  94. - (NSURLSessionDataTask *)GET:(NSString *)URLString
  95. parameters:(id)parameters
  96. success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
  97. failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
  98. {
  99. return [self GET:URLString parameters:parameters progress:nil success:success failure:failure];
  100. }
  101. - (NSURLSessionDataTask *)GET:(NSString *)URLString
  102. parameters:(id)parameters
  103. progress:(void (^)(NSProgress * _Nonnull))downloadProgress
  104. success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success
  105. failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
  106. {
  107. NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"GET"
  108. URLString:URLString
  109. parameters:parameters
  110. uploadProgress:nil
  111. downloadProgress:downloadProgress
  112. success:success
  113. failure:failure];
  114. [dataTask resume];
  115. return dataTask;
  116. }
  117. - (NSURLSessionDataTask *)HEAD:(NSString *)URLString
  118. parameters:(id)parameters
  119. success:(void (^)(NSURLSessionDataTask *task))success
  120. failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
  121. {
  122. NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"HEAD" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:^(NSURLSessionDataTask *task, __unused id responseObject) {
  123. if (success) {
  124. success(task);
  125. }
  126. } failure:failure];
  127. [dataTask resume];
  128. return dataTask;
  129. }
  130. - (NSURLSessionDataTask *)POST:(NSString *)URLString
  131. parameters:(id)parameters
  132. success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
  133. failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
  134. {
  135. return [self POST:URLString parameters:parameters progress:nil success:success failure:failure];
  136. }
  137. - (NSURLSessionDataTask *)POST:(NSString *)URLString
  138. parameters:(id)parameters
  139. progress:(void (^)(NSProgress * _Nonnull))uploadProgress
  140. success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success
  141. failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
  142. {
  143. NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"POST" URLString:URLString parameters:parameters uploadProgress:uploadProgress downloadProgress:nil success:success failure:failure];
  144. [dataTask resume];
  145. return dataTask;
  146. }
  147. - (NSURLSessionDataTask *)POST:(NSString *)URLString
  148. parameters:(nullable id)parameters
  149. constructingBodyWithBlock:(nullable void (^)(id<AFMultipartFormData> _Nonnull))block
  150. success:(nullable void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success
  151. failure:(nullable void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
  152. {
  153. return [self POST:URLString parameters:parameters constructingBodyWithBlock:block progress:nil success:success failure:failure];
  154. }
  155. - (NSURLSessionDataTask *)POST:(NSString *)URLString
  156. parameters:(id)parameters
  157. constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
  158. progress:(nullable void (^)(NSProgress * _Nonnull))uploadProgress
  159. success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
  160. failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
  161. {
  162. NSError *serializationError = nil;
  163. NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:&serializationError];
  164. if (serializationError) {
  165. if (failure) {
  166. dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
  167. failure(nil, serializationError);
  168. });
  169. }
  170. return nil;
  171. }
  172. __block NSURLSessionDataTask *task = [self uploadTaskWithStreamedRequest:request progress:uploadProgress completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
  173. if (error) {
  174. if (failure) {
  175. failure(task, error);
  176. }
  177. } else {
  178. if (success) {
  179. success(task, responseObject);
  180. }
  181. }
  182. }];
  183. [task resume];
  184. return task;
  185. }
  186. - (NSURLSessionDataTask *)PUT:(NSString *)URLString
  187. parameters:(id)parameters
  188. success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
  189. failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
  190. {
  191. NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PUT" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:success failure:failure];
  192. [dataTask resume];
  193. return dataTask;
  194. }
  195. - (NSURLSessionDataTask *)PATCH:(NSString *)URLString
  196. parameters:(id)parameters
  197. success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
  198. failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
  199. {
  200. NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PATCH" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:success failure:failure];
  201. [dataTask resume];
  202. return dataTask;
  203. }
  204. - (NSURLSessionDataTask *)DELETE:(NSString *)URLString
  205. parameters:(id)parameters
  206. success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
  207. failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
  208. {
  209. NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"DELETE" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:success failure:failure];
  210. [dataTask resume];
  211. return dataTask;
  212. }
  213. - (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method
  214. URLString:(NSString *)URLString
  215. parameters:(id)parameters
  216. uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress
  217. downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress
  218. success:(void (^)(NSURLSessionDataTask *, id))success
  219. failure:(void (^)(NSURLSessionDataTask *, NSError *))failure
  220. {
  221. NSError *serializationError = nil;
  222. NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError];
  223. if (serializationError) {
  224. if (failure) {
  225. dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
  226. failure(nil, serializationError);
  227. });
  228. }
  229. return nil;
  230. }
  231. __block NSURLSessionDataTask *dataTask = nil;
  232. dataTask = [self dataTaskWithRequest:request
  233. uploadProgress:uploadProgress
  234. downloadProgress:downloadProgress
  235. completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
  236. if (error) {
  237. if (failure) {
  238. failure(dataTask, error);
  239. }
  240. } else {
  241. if (success) {
  242. success(dataTask, responseObject);
  243. }
  244. }
  245. }];
  246. return dataTask;
  247. }
  248. #pragma mark - NSObject
  249. - (NSString *)description {
  250. return [NSString stringWithFormat:@"<%@: %p, baseURL: %@, session: %@, operationQueue: %@>", NSStringFromClass([self class]), self, [self.baseURL absoluteString], self.session, self.operationQueue];
  251. }
  252. #pragma mark - NSSecureCoding
  253. + (BOOL)supportsSecureCoding {
  254. return YES;
  255. }
  256. - (instancetype)initWithCoder:(NSCoder *)decoder {
  257. NSURL *baseURL = [decoder decodeObjectOfClass:[NSURL class] forKey:NSStringFromSelector(@selector(baseURL))];
  258. NSURLSessionConfiguration *configuration = [decoder decodeObjectOfClass:[NSURLSessionConfiguration class] forKey:@"sessionConfiguration"];
  259. if (!configuration) {
  260. NSString *configurationIdentifier = [decoder decodeObjectOfClass:[NSString class] forKey:@"identifier"];
  261. if (configurationIdentifier) {
  262. #if (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1100)
  263. configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:configurationIdentifier];
  264. #else
  265. configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:configurationIdentifier];
  266. #endif
  267. }
  268. }
  269. self = [self initWithBaseURL:baseURL sessionConfiguration:configuration];
  270. if (!self) {
  271. return nil;
  272. }
  273. self.requestSerializer = [decoder decodeObjectOfClass:[AFHTTPRequestSerializer class] forKey:NSStringFromSelector(@selector(requestSerializer))];
  274. self.responseSerializer = [decoder decodeObjectOfClass:[AFHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))];
  275. AFSecurityPolicy *decodedPolicy = [decoder decodeObjectOfClass:[AFSecurityPolicy class] forKey:NSStringFromSelector(@selector(securityPolicy))];
  276. if (decodedPolicy) {
  277. self.securityPolicy = decodedPolicy;
  278. }
  279. return self;
  280. }
  281. - (void)encodeWithCoder:(NSCoder *)coder {
  282. [super encodeWithCoder:coder];
  283. [coder encodeObject:self.baseURL forKey:NSStringFromSelector(@selector(baseURL))];
  284. if ([self.session.configuration conformsToProtocol:@protocol(NSCoding)]) {
  285. [coder encodeObject:self.session.configuration forKey:@"sessionConfiguration"];
  286. } else {
  287. [coder encodeObject:self.session.configuration.identifier forKey:@"identifier"];
  288. }
  289. [coder encodeObject:self.requestSerializer forKey:NSStringFromSelector(@selector(requestSerializer))];
  290. [coder encodeObject:self.responseSerializer forKey:NSStringFromSelector(@selector(responseSerializer))];
  291. [coder encodeObject:self.securityPolicy forKey:NSStringFromSelector(@selector(securityPolicy))];
  292. }
  293. #pragma mark - NSCopying
  294. - (instancetype)copyWithZone:(NSZone *)zone {
  295. AFHTTPSessionManager *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL sessionConfiguration:self.session.configuration];
  296. HTTPClient.requestSerializer = [self.requestSerializer copyWithZone:zone];
  297. HTTPClient.responseSerializer = [self.responseSerializer copyWithZone:zone];
  298. HTTPClient.securityPolicy = [self.securityPolicy copyWithZone:zone];
  299. return HTTPClient;
  300. }
  301. @end