XSHttpTool.m 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. //
  2. // XSHttpTool.m
  3. //
  4. // Created by xiaos on 14/11/10.
  5. // Copyright © 2015年 com.xsdota. All rights reserved.
  6. //
  7. #import "XSHttpTool.h"
  8. //#import "MBProgressHUD+Extend.h"
  9. @implementation XSHttpTool
  10. #pragma mark - GET
  11. + (void)GET:(NSString *)requestKey
  12. param:(NSDictionary *)param
  13. success:(successBlock)success
  14. failure:(failureBlock)failure {
  15. [self checkReachability];
  16. NSString *URLStr = [self getURLStrByRequsetKey:requestKey];
  17. [[XSHttpTool sharedManager] GET:URLStr parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {
  18. NSLog(@"%@",operation.response.URL);
  19. success(responseObject);
  20. } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
  21. failure(error);
  22. }];
  23. }
  24. + (void)GETCache:(NSString *)requestKey
  25. param:(NSDictionary *)param
  26. success:(successBlock)success
  27. failure:(failureBlock)failure {
  28. [self checkReachability];
  29. NSString *URLStr = [self getURLStrByRequsetKey:requestKey];
  30. AFHTTPRequestOperationManager *mgr = [XSHttpTool sharedManager];
  31. mgr.requestSerializer.cachePolicy = NSURLRequestReturnCacheDataElseLoad;
  32. [mgr GET:URLStr parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {
  33. NSLog(@"%@",operation.response.URL);
  34. success(responseObject);
  35. } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
  36. failure(error);
  37. }];
  38. }
  39. #pragma mark - POST
  40. + (void)POST:(NSString *)requestKey
  41. param:(NSDictionary *)param
  42. success:(successBlock)success
  43. failure:(failureBlock)failure
  44. {
  45. [self checkReachability];
  46. NSString *URLStr = [self getURLStrByRequsetKey:requestKey];
  47. [[XSHttpTool sharedManager] POST:URLStr
  48. parameters:param
  49. success:^(AFHTTPRequestOperation *operation, id responseObject) {
  50. NSLog(@"%@",operation.response.URL);
  51. success(responseObject);
  52. } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
  53. failure(error);
  54. }];
  55. }
  56. + (void)UpLoadData:(NSData *)data
  57. to:(NSString *)requestKey
  58. withParamName:(NSString *)paramName
  59. fileName:(NSString *)fileName
  60. mimeType:(NSString *)type
  61. param:(NSDictionary *)param
  62. success:(successBlock)success
  63. failure:(failureBlock)failure
  64. uploadProgress:(progressBlock)uploadProgress {
  65. [self checkReachability];
  66. NSString *URLStr = [self getURLStrByRequsetKey:requestKey];
  67. AFHTTPRequestOperation *operation =
  68. [[XSHttpTool sharedManager]
  69. POST:URLStr
  70. parameters:param
  71. constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
  72. [formData appendPartWithFileData:data name:paramName fileName:fileName mimeType:type];
  73. } success:^(AFHTTPRequestOperation *operation, id responseObject) {
  74. success(responseObject);
  75. } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
  76. failure(error);
  77. }];
  78. [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
  79. CGFloat percent = totalBytesWritten * 1.0 / totalBytesExpectedToWrite;
  80. uploadProgress(percent);
  81. }];
  82. }
  83. + (void)upLoadImages:(NSArray *)images
  84. to:(NSString *)requestKey
  85. withParamName:(NSString *)paramName
  86. ratio:(float)ratio
  87. param:(NSDictionary *)param
  88. success:(successBlock)success
  89. failure:(failureBlock)failure
  90. uploadProgress:(progressBlock)uploadProgress {
  91. [self checkReachability];
  92. NSString *URLStr = [self getURLStrByRequsetKey:requestKey];
  93. AFHTTPRequestOperation *operation =
  94. [[XSHttpTool sharedManager]
  95. POST:URLStr
  96. parameters:param
  97. constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
  98. NSUInteger i = 0;
  99. NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
  100. [formatter setDateFormat:@"yyyyMMddHHmm"];
  101. NSString *dateString = [formatter stringFromDate:[NSDate date]];
  102. for (UIImage *image in images) {
  103. NSString *fileName = [NSString stringWithFormat:@"%@_%lu.png",dateString,(unsigned long)i];
  104. NSData *imageData;
  105. if (ratio > 0.0f && ratio < 1.0f) {
  106. imageData = UIImageJPEGRepresentation(image, ratio);
  107. }else{
  108. imageData = UIImageJPEGRepresentation(image, 1.0f);
  109. }
  110. [formData appendPartWithFileData:imageData name:paramName fileName:fileName mimeType:@"image/jpg/png/jpeg"];
  111. }
  112. } success:^(AFHTTPRequestOperation *operation, id responseObject) {
  113. success(responseObject);
  114. } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
  115. failure(error);
  116. }];
  117. [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
  118. CGFloat percent = totalBytesWritten * 1.0 / totalBytesExpectedToWrite;
  119. uploadProgress(percent);
  120. }];
  121. }
  122. #pragma mark - 设置单例 超时请求响应解析
  123. + (AFHTTPRequestOperationManager *)sharedManager {
  124. AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
  125. [manager.requestSerializer setTimeoutInterval:TIMEOUT];
  126. // manager.
  127. //header 设置
  128. // [manager.requestSerializer setValue:K_PASS_IP forHTTPHeaderField:@"Host"];
  129. // [manager.requestSerializer setValue:@"max-age=0" forHTTPHeaderField:@"Cache-Control"];
  130. // [manager.requestSerializer setValue:@"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" forHTTPHeaderField:@"Accept"];
  131. // [manager.requestSerializer setValue:@"zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3" forHTTPHeaderField:@"Accept-Language"];
  132. // [manager.requestSerializer setValue:@"gzip, deflate" forHTTPHeaderField:@"Accept-Encoding"];
  133. // [manager.requestSerializer setValue:@"keep-alive" forHTTPHeaderField:@"Connection"];
  134. // [manager.requestSerializer setValue:@"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:35.0) Gecko/20100101 Firefox/35.0" forHTTPHeaderField:@"User-Agent"];
  135. manager.requestSerializer.cachePolicy = 0;
  136. manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"text/html", @"application/json", nil];
  137. return manager;
  138. }
  139. #pragma mark - 检测网络连接状态
  140. + (void)checkReachability
  141. {
  142. [[AFNetworkReachabilityManager sharedManager] startMonitoring];
  143. // 连接状态回调处理
  144. [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
  145. switch (status) {
  146. case AFNetworkReachabilityStatusUnknown:
  147. NSLog(@"Unkonw Collection");
  148. break;
  149. case AFNetworkReachabilityStatusNotReachable:
  150. NSLog(@"网络未连接");
  151. // [MBProgressHUD showError:@"网络未连接"];
  152. break;
  153. case AFNetworkReachabilityStatusReachableViaWWAN:
  154. NSLog(@"WWAN Collection");
  155. break;
  156. case AFNetworkReachabilityStatusReachableViaWiFi:
  157. NSLog(@"WiFi Collection");
  158. break;
  159. }
  160. }];
  161. }
  162. #pragma mark - 拼接出完整的URL
  163. + (NSString *)getURLStrByRequsetKey:(NSString *)requestKey
  164. {
  165. /** 可以传入完整URL地址 会自动覆盖主API */
  166. if ([requestKey hasPrefix:@"http://"] || [requestKey hasPrefix:@"https://"]) {
  167. return [requestKey stringByRemovingPercentEncoding];
  168. }
  169. NSString *URLStr = [[HOST_ADDRESS stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%@",EXTRA_STR,requestKey]] stringByRemovingPercentEncoding];
  170. return URLStr;
  171. }
  172. #pragma mark - 自定义cache管理
  173. + (NSString *)cachesDirectory {
  174. NSString * cachesDirectory = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
  175. return cachesDirectory;
  176. }
  177. + (NSString *)cachePathWithIdentifier:(NSString *)cacheIdentifier {
  178. NSString * cachePath = [self cachesDirectory];
  179. cachePath = [cachePath stringByAppendingPathComponent:cacheIdentifier];
  180. BOOL isDirectory = NO;
  181. BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:cachePath isDirectory:&isDirectory];
  182. if (fileExists == NO || isDirectory) {
  183. BOOL createFileSuccess = [[NSFileManager defaultManager] createFileAtPath:cachePath contents:nil attributes:nil];
  184. if (createFileSuccess == NO) {
  185. NSLog(@"创建缓存文件失败"); //
  186. return nil;
  187. }
  188. else {
  189. NSLog(@"创建缓存文件成功"); //
  190. }
  191. }
  192. else {
  193. NSLog(@"缓存文件之前已存在"); //
  194. }
  195. return cachePath;
  196. }
  197. + (BOOL)saveCache:(NSDictionary *)cache
  198. withIdentifier:(NSString *)cacheIdentifier {
  199. NSCAssert([cache isKindOfClass:[NSDictionary class]], @"缓存对象不是字典类型");
  200. NSString * cachePath = [self cachePathWithIdentifier:cacheIdentifier];
  201. BOOL saveSuccess = [cache writeToFile:cachePath atomically:YES];
  202. if (saveSuccess) {
  203. NSLog(@"储存缓存记录成功");
  204. return saveSuccess;
  205. }
  206. else {
  207. NSLog(@"储存缓存记录失败");
  208. return saveSuccess;
  209. }
  210. }
  211. + (NSDictionary *)cacheWithIdentifier:(NSString *)cacheIdentifier {
  212. NSString * cachePath = [XSHttpTool cachePathWithIdentifier:cacheIdentifier];
  213. NSDictionary * cache = [NSDictionary dictionaryWithContentsOfFile:cachePath];
  214. if (cache) {
  215. NSLog(@"并不存在缓存");
  216. }
  217. NSError * error = nil;
  218. NSDictionary * cacheFileAttributes = [[NSFileManager defaultManager]attributesOfItemAtPath:cachePath error:&error];
  219. if (error) {
  220. NSLog(@"缓存已过期");
  221. }
  222. else if ([[NSDate date]timeIntervalSince1970] - [cacheFileAttributes.fileModificationDate timeIntervalSince1970] > JSON_CACHE_DURATION) {
  223. NSLog(@"缓存已过期");
  224. BOOL removeCacheSuccess = [[NSFileManager defaultManager] removeItemAtPath:cachePath error:&error];
  225. if (removeCacheSuccess) {
  226. NSLog(@"移除已过期的缓存成功");
  227. }
  228. else {
  229. NSLog(@"移除已过期的缓存失败");
  230. }
  231. return nil;
  232. }
  233. else {
  234. }
  235. return cache;
  236. }
  237. @end