HttpManager.m 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  1. //
  2. // HttpManager.m
  3. // TheoryNetwork
  4. //
  5. // Created by tederen on 2019/9/25.
  6. // Copyright © 2019 tederen. All rights reserved.
  7. //
  8. #import "HttpManager.h"
  9. @interface HttpManager ()
  10. @end
  11. @implementation HttpManager
  12. TDShareInstance_implementation(HttpManager)
  13. - (void)GET:(NSString *)URLString
  14. parameters:(nullable id)parameters
  15. success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
  16. failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure {
  17. [self.manager GET:URLString parameters:parameters progress:nil success:success failure:failure];
  18. }
  19. - (void)POST:(NSString *)URLString
  20. parameters:(nullable id)parameters
  21. success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
  22. failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure {
  23. [self.manager POST:URLString parameters:parameters progress:nil success:success failure:failure];
  24. }
  25. - (void)startRequestWithUrl:(NSString *)url method:(NSString *)method params:(NSDictionary *)params{
  26. NSError *error;
  27. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
  28. NSString *jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
  29. AFURLSessionManager *manager = [[AFURLSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
  30. NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:method URLString:url parameters:nil error:nil];
  31. request.timeoutInterval = 30;
  32. [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
  33. [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
  34. // manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/plain"];
  35. [request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
  36. [[manager dataTaskWithRequest:request uploadProgress:^(NSProgress * _Nonnull uploadProgress) {
  37. } downloadProgress:^(NSProgress * _Nonnull downloadProgress) {
  38. } completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
  39. if (!error) {
  40. NSLog(@"Reply JOSN:%@",responseObject);
  41. }else{
  42. NSLog(@"ERROR:%@,%@,%@",error,response,responseObject);
  43. }
  44. }] resume] ;
  45. }
  46. - (void)DeleteWithUrl:(NSString *)url
  47. parameters:(NSDictionary *)parameters
  48. success:(void (^)(id responseObject))successful
  49. failure:(void (^) (NSError *error))failure{
  50. if (url.length==0) {
  51. return;
  52. }
  53. if (![url hasPrefix:@"http"]) {
  54. url = [BaseUrl stringByAppendingString:url];
  55. }
  56. [self DeleteUrl:url
  57. parameters:parameters
  58. responseStyle:JOSN
  59. success:successful
  60. failure:failure];
  61. }
  62. - (void)DeleteUrl:(NSString *)url
  63. parameters:(NSDictionary *)parameters
  64. success:(void (^)(id responseObject))successful
  65. failure:(void (^) (NSError *error))failure{
  66. [self DeleteUrl:url
  67. parameters:parameters
  68. responseStyle:JOSN
  69. success:successful
  70. failure:failure];
  71. }
  72. - (void)DeleteUrl:(NSString *)url
  73. parameters:(NSDictionary *)parameters
  74. responseStyle:(FWZRsponseStyle)style
  75. success:(void (^)(id responseObject))successful
  76. failure:(void (^) (NSError *error))failure {
  77. switch (style) {
  78. case JOSN:{
  79. self.manager.responseSerializer = [AFJSONResponseSerializer serializer];
  80. }break;
  81. case XML:{
  82. self.manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
  83. }break;
  84. case DATA:{
  85. self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
  86. }break;
  87. }
  88. NSError *error = nil;
  89. //判断接口是否是空值
  90. if (url.length == 0 || [url isEqualToString:@""]) {
  91. failure(error);
  92. }
  93. self.manager.requestSerializer.HTTPMethodsEncodingParametersInURI = [NSSet setWithObjects:@"GET", @"HEAD", nil];
  94. //开始请求内容
  95. [self.manager DELETE:url
  96. parameters:parameters
  97. success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  98. [self reLoginApp:task];
  99. successful(responseObject);
  100. }
  101. failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  102. [self reLoginApp:task];
  103. failure(error);
  104. }];
  105. }
  106. - (void)GETUrl:(NSString *)url
  107. parameters:(NSDictionary *)parameters
  108. success:(void (^)(id responseObject))successful
  109. failure:(void (^) (NSError *error))failure
  110. {
  111. [self GETUrl:url parameters:parameters responseStyle:JOSN success:successful failure:failure];
  112. }
  113. - (void)GETUrl:(NSString *)url
  114. parameters:(NSDictionary *)parameters
  115. responseStyle:(FWZRsponseStyle)style
  116. success:(void (^)(id responseObject))successful
  117. failure:(void (^) (NSError *error))failure {
  118. switch (style) {
  119. case JOSN:{
  120. self.manager.responseSerializer = [AFJSONResponseSerializer serializer];
  121. }break;
  122. case XML:{
  123. self.manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
  124. }break;
  125. case DATA:{
  126. self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
  127. }break;
  128. }
  129. NSError *error = nil;
  130. //判断接口是否是空值
  131. if (url.length == 0 || [url isEqualToString:@""]) {
  132. failure(error);
  133. }
  134. //开始请求内容
  135. [self.manager GET:url parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
  136. //如果需要填充进度内容,可以直接进行内容添加
  137. } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  138. [self reLoginApp:task];
  139. successful(responseObject);
  140. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  141. [self reLoginApp:task];
  142. failure(error);
  143. }];
  144. }
  145. /// 只需要传 api url 即可
  146. - (void)GETWithUrl:(NSString *)url
  147. parameters:(NSDictionary *)parameters
  148. success:(void (^)(id responseObject))successful
  149. failure:(void (^) (NSError *error))failure{
  150. if (url.length==0) {
  151. return;
  152. }
  153. if (![url hasPrefix:@"http"]) {
  154. url = [BaseUrl stringByAppendingString:url];
  155. }
  156. [self GETUrl:url parameters:parameters responseStyle:JOSN success:successful failure:failure];
  157. }
  158. /**
  159.  POST请求接口
  160.  */
  161. /// 只需要传 api url 即可
  162. - (void)POSTWithUrl:(NSString *)url
  163. parameters:(NSDictionary *)parameters
  164. success:(void (^)(id responseObject))successful
  165. failure:(void (^) (NSError *error))failure{
  166. if (url.length==0) {
  167. return;
  168. }
  169. if (![url hasPrefix:@"http"]) {
  170. url = [BaseUrl stringByAppendingString:url];
  171. }
  172. [self POSTUrl:url parameters:parameters responseStyle:JOSN success:successful failure:failure];
  173. }
  174. //responseStyle:(responseStyle)style
  175. - (void)POSTUrl:(NSString *)url
  176. parameters:(NSDictionary *)parameters
  177. success:(void (^)(id responseObject))successful
  178. failure:(void (^) (NSError *error))failure
  179. {
  180. [self POSTUrl:url
  181. parameters:parameters
  182. responseStyle:DATA
  183. success:successful
  184. failure:failure];
  185. }
  186. - (void)POSTUrl:(NSString *)url
  187. parameters:(NSDictionary *)parameters
  188. responseStyle:(FWZRsponseStyle)style
  189. success:(void (^)(id responseObject))successful
  190. failure:(void (^) (NSError *error))failure
  191. {
  192. switch (style) {
  193. case JOSN:{
  194. self.manager.responseSerializer = [AFJSONResponseSerializer serializer];
  195. }break;
  196. case XML:{
  197. self.manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
  198. }break;
  199. case DATA:{
  200. self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
  201. }break;
  202. }
  203. NSError *error = nil;
  204. if (url.length == 0 || [url isEqualToString:@""]) { failure(error); }
  205. [self.manager POST:url parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
  206. } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  207. [self reLoginApp:task];
  208. successful(responseObject);
  209. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  210. [self reLoginApp:task];
  211. failure(error);
  212. }];
  213. }
  214. /**
  215. 图片上传接口(上传音频与图片是一致的,需要更改的只是 mimeType类型,根据要求设置对应的格式即可)
  216. @param url 请求接口
  217. @param paramters 请求参数
  218. @param pictureData 图片数据
  219. @param pictureKey 与后台约定的 文件key
  220. @param successful 成功返回
  221. @param failure 失败返回
  222. */
  223. - (void)HeaderUploadUrl:(NSString *)url
  224. parameters:(NSDictionary *)paramters
  225. pictureData:(NSData *)pictureData
  226. pictureKey:(NSString *)pictureKey
  227. success:(void (^) (id responseObject))successful
  228. failure:(void (^) (NSError *error))failure
  229. {
  230. NSError *error = nil;
  231. //接口URL为空
  232. if (url.length == 0 || [url isEqualToString:@""] ) {
  233. failure(error);
  234. }
  235. // //传入参数为空
  236. // if ([ZYCTool isNullToDictionary:paramters]) {
  237. // failure(error);
  238. // }
  239. //传入上传图片数据为空(NSData)
  240. if (pictureData.length == 0) {
  241. failure(error);
  242. }
  243. //上传图片,服务器端文件名
  244. if (pictureKey.length == 0 || [pictureKey isEqualToString:@""]) {
  245. failure(error);
  246. }
  247. [self.manager POST:url parameters:paramters constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
  248. //对上传完文件的配置
  249. //获取当前时间(int 时间戳转换)
  250. int nowDate = [[NSString stringWithFormat:@"%ld",(long)[[NSDate date] timeIntervalSince1970]]intValue];
  251. NSString *fileName = [NSString stringWithFormat:@"%d.jpg",nowDate];
  252. //参数介绍
  253. //fileData : 图片资源 name : 预定key fileName : 文件名 mimeType : 资源类型(根据后台进行对应配置)
  254. [formData appendPartWithFileData:pictureData name:pictureKey fileName:fileName mimeType:@"image/jpeg"];
  255. } progress:^(NSProgress * _Nonnull uploadProgress) {
  256. //上传进度
  257. dispatch_sync(dispatch_get_main_queue(), ^{
  258. // progress ? progress(uploadProgress) : nil;
  259. });
  260. } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  261. successful(responseObject);
  262. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  263. //可以将http响应码返回,以便于判断错误
  264. failure(error);
  265. }];
  266. }
  267. /**
  268. 图片上传接口(上传音频与图片是一致的,需要更改的只是 mimeType类型,根据要求设置对应的格式即可)
  269. @param url 请求接口
  270. @param paramters 请求参数
  271. @param array 图片数组
  272. @param pictureKey 与后台约定的 文件key
  273. @param successful 成功返回
  274. @param failure 失败返回
  275. */
  276. - (void)HeaderUploadUrl:(NSString *)url
  277. parameters:(NSDictionary *)paramters
  278. pictureArray:(NSArray *)array
  279. pictureKey:(NSString *)pictureKey
  280. success:(void (^) (id responseObject))successful
  281. failure:(void (^) (NSError *error))failure
  282. {
  283. NSError *error = nil;
  284. //接口URL为空
  285. if (url.length == 0 || [url isEqualToString:@""] ) {
  286. failure(error);
  287. }
  288. // //传入参数为空
  289. // if ([ZYCTool isNullToDictionary:paramters]) {
  290. // failure(error);
  291. // }
  292. //传入上传图片数据为空(NSData)
  293. if (array.count == 0) {
  294. failure(error);
  295. }
  296. //上传图片,服务器端文件名
  297. if (pictureKey.length == 0 || [pictureKey isEqualToString:@""]) {
  298. failure(error);
  299. }
  300. [self.manager POST:url parameters:paramters constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
  301. //对上传完文件的配置
  302. //获取当前时间(int 时间戳转换)
  303. for (NSInteger i = 0; i < array.count; i++) {
  304. int nowDate = [[NSString stringWithFormat:@"%ld",(long)[[NSDate date] timeIntervalSince1970]]intValue];
  305. NSString *fileName = [NSString stringWithFormat:@"%d%ld.jpg",nowDate,(long)i];
  306. //参数介绍
  307. //fileData : 图片资源 name : 预定key fileName : 文件名 mimeType : 资源类型(根据后台进行对应配置)
  308. [formData appendPartWithFileData:array[i] name:pictureKey fileName:fileName mimeType:@"image/jpeg"];
  309. }
  310. } progress:^(NSProgress * _Nonnull uploadProgress) {
  311. //上传进度
  312. dispatch_sync(dispatch_get_main_queue(), ^{
  313. // progress ? progress(uploadProgress) : nil;
  314. });
  315. } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  316. [self reLoginApp:task];
  317. successful(responseObject);
  318. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  319. [self reLoginApp:task];
  320. //可以将http响应码返回,以便于判断错误
  321. failure(error);
  322. }];
  323. }
  324. - (void)HeaderUploadFileUrl:(NSString *)url
  325. parameters:(NSDictionary *)paramters
  326. fileData:(NSData *)fileData
  327. fileKey:(NSString *)fileKey
  328. fileName:(NSString *)fileName
  329. mimeType:(NSString *)mimeType
  330. success:(void (^) (id responseObject))successful
  331. failure:(void (^) (NSError *error))failure
  332. {
  333. NSError *error = nil;
  334. //接口URL为空
  335. if (url.length == 0 || [url isEqualToString:@""] ) {
  336. failure(error);
  337. }
  338. //传入上传图片数据为空(NSData)
  339. if (fileData.length == 0) {
  340. failure(error);
  341. }
  342. //上传图片,服务器端文件名
  343. if (fileKey.length == 0 || [fileKey isEqualToString:@""]) {
  344. failure(error);
  345. }
  346. self.manager.responseSerializer = [AFJSONResponseSerializer serializer];
  347. [self.manager POST:url parameters:paramters constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
  348. //fileData : 图片资源 name : 预定key fileName : 文件名 mimeType : 资源类型(根据后台进行对应配置)
  349. [formData appendPartWithFileData:fileData name:fileKey fileName:fileName mimeType:mimeType];
  350. } progress:^(NSProgress * _Nonnull uploadProgress) {
  351. //上传进度
  352. dispatch_sync(dispatch_get_main_queue(), ^{
  353. // progress ? progress(uploadProgress) : nil;
  354. });
  355. } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  356. [self reLoginApp:task];
  357. successful(responseObject);
  358. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  359. [self reLoginApp:task];
  360. //可以将http响应码返回,以便于判断错误
  361. failure(error);
  362. }];
  363. }
  364. //
  365. //
  366. ///**
  367. // 下载文件接口
  368. //
  369. // @param url 请求接口
  370. // @param progress 下载进度
  371. // @param downloadFilePath 文件保存路径
  372. // @param successful  返回路径内容
  373. // @param failure 失败返回
  374. // */
  375. //- (void)downloadUrl:(NSString *)url
  376. //           progress:(HttpProgress)progress
  377. //   downloadFilePath:(NSString *)downloadFilePath
  378. //            success:(void (^) (id responseObject))successful
  379. //            failure:(void (^) (NSError *error, ParamtersJudgeCode  judgeCode))failure;
  380. //
  381. //
  382. //
  383. ///**
  384. // 下载文件接口
  385. // @param url 请求接口
  386. // @param progress 下载进度
  387. // @param downloadFilePath 文件保存路径
  388. // @param successful  返回路径内容
  389. // @param failure 失败返回
  390. // */
  391. //- (void)downloadUrl:(NSString *)url
  392. //        progress:(HttpProgress)progress
  393. //        downloadFilePath:(NSString *)downloadFilePath
  394. //        success:(void (^) (id responseObject))successful
  395. //        failure:(void (^) (NSError *error, ParamtersJudgeCode  judgeCode))failure
  396. //  {
  397. //    //下载地址
  398. //    NSURL *downloadURL = [NSURL URLWithString:url];
  399. //    //设置请求
  400. //    NSURLRequest *request = [NSURLRequest requestWithURL:downloadURL];
  401. //    //下载操作
  402. //    [_sessionManager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
  403. //        //下载进度
  404. //        dispatch_sync(dispatch_get_main_queue(), ^{
  405. //            progress ? progress(downloadProgress) : nil;
  406. //        });
  407. //
  408. //    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
  409. //        //拼接缓存目录
  410. //        NSString *downloadPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadFilePath ? downloadFilePath : @"Download"];
  411. //        //打开文件管理器
  412. //        NSFileManager *fileManager = [NSFileManager defaultManager];
  413. //        //创建Download目录
  414. //        [fileManager createDirectoryAtPath:downloadPath withIntermediateDirectories:YES attributes:nil error:nil];
  415. //        //拼接文件路径
  416. //        NSString *filePath = [downloadPath stringByAppendingPathComponent:response.suggestedFilename];
  417. //        //返回文件位置的URL路径
  418. //        return [NSURL fileURLWithPath:filePath];
  419. //    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
  420. //        NSInteger responseCode = [self showResponseCode:response];
  421. //        if (responseCode != 200) {
  422. //            successful ? successful(filePath.absoluteString): nil;
  423. //        }else {
  424. //            failure(error, UploadFailed);
  425. //        }
  426. //    }];
  427. //}
  428. //
  429. - (void)downloadUrl:(NSString *)url
  430. downloadFilePath:(NSString *)downloadFilePath
  431. success:(void (^) (id responseObject))successful
  432. failure:(void (^) (NSError *error))failure
  433. {
  434. //下载地址
  435. NSURL *downloadURL = [NSURL URLWithString:url];
  436. //设置请求
  437. NSURLRequest *request = [NSURLRequest requestWithURL:downloadURL];
  438. //下载操作
  439. [_manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
  440. } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
  441. //拼接缓存目录
  442. NSString *downloadPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadFilePath ? downloadFilePath : @"Download"];
  443. //打开文件管理器
  444. NSFileManager *fileManager = [NSFileManager defaultManager];
  445. //创建Download目录
  446. [fileManager createDirectoryAtPath:downloadPath withIntermediateDirectories:YES attributes:nil error:nil];
  447. //拼接文件路径
  448. NSString *filePath = [downloadPath stringByAppendingPathComponent:response.suggestedFilename];
  449. //返回文件位置的URL路径
  450. return [NSURL fileURLWithPath:filePath];
  451. } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
  452. failure(error);
  453. }];
  454. }
  455. //
  456. //
  457. ///**
  458. // POST请求接口
  459. // */
  460. //
  461. //
  462. //- (void)POSTUrl:(NSString *)url parameters:(NSDictionary *)parameters success:(void (^)(id responseObject))successful
  463. //failure:(void (^) (NSError *error))failure
  464. //{
  465. // NSError *error = nil;
  466. // if (url.length == 0 || [url isEqualToString:@""]) {
  467. // failure(error);
  468. // }
  469. // [self.manager POST:url parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
  470. //
  471. // } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  472. // successful(responseObject);
  473. //
  474. // } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  475. // failure(error);
  476. // }];
  477. //
  478. //}
  479. - (void)PUTUrl:(NSString *)url parameters:(NSDictionary *)parameters success:(void (^)(id responseObject))successful
  480. failure:(void (^) (NSError *error))failure{
  481. self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
  482. NSError *error = nil;
  483. if (url.length == 0 || [url isEqualToString:@""]) {
  484. failure(error);
  485. }
  486. NSLog(@"url:%@",url);
  487. [self.manager PUT:url parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  488. [self reLoginApp:task];
  489. successful(responseObject);
  490. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  491. [self reLoginApp:task];
  492. failure(error);
  493. }];
  494. }
  495. - (void)PUTUrl:(NSString *)url
  496. parameters:(NSDictionary *)parameters
  497. responseStyle:(FWZRsponseStyle)style
  498. success:(void (^)(id responseObject))successful
  499. failure:(void (^) (NSError *error))failure
  500. {
  501. switch (style) {
  502. case JOSN:{
  503. self.manager.responseSerializer = [AFJSONResponseSerializer serializer];
  504. }break;
  505. case XML:{
  506. self.manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
  507. }break;
  508. case DATA:{
  509. self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
  510. }break;
  511. }
  512. NSError *error = nil;
  513. if (url.length == 0 || [url isEqualToString:@""]) { failure(error); }
  514. [self.manager PUT:url parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  515. [self reLoginApp:task];
  516. successful(responseObject);
  517. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  518. [self reLoginApp:task];
  519. failure(error);
  520. }];
  521. }
  522. +(NSURLSessionUploadTask*)uploadTaskUrl:(NSURL*)uploadPage params:(NSDictionary*)params files:(NSArray<NSDictionary<NSString*,id>*>*)fileDatas completion:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionBlock {
  523. NSLog(@"url %@\nparam %@",uploadPage,params);
  524. NSError* error = NULL;
  525. NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:[uploadPage absoluteString] parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
  526. for (int i=0; i<fileDatas.count; i++) {
  527. NSDictionary* unitData = fileDatas[i];
  528. if (unitData && [unitData objectForKey:@"key"] && [unitData objectForKey:@"filename"] && [unitData objectForKey:@"data"]) {
  529. if ([[unitData objectForKey:@"data"] isKindOfClass:[NSData class]]) {
  530. [formData appendPartWithFileData:(NSData*)[unitData objectForKey:@"data"] name:[unitData objectForKey:@"key"] fileName:[unitData objectForKey:@"filename"] mimeType:@"multipart/form-data"];
  531. }else if([[unitData objectForKey:@"data"] isKindOfClass:[NSURL class]]){
  532. [formData appendPartWithFileURL:(NSURL*)[unitData objectForKey:@"data"] name:[unitData objectForKey:@"key"] fileName:[unitData objectForKey:@"filename"] mimeType:@"multipart/form-data" error:nil];
  533. }
  534. }
  535. }
  536. } error:&error];
  537. NSLog(@"error %@",error);
  538. // 将 NSURLRequest 与 completionBlock 包装为 NSURLSessionUploadTask
  539. AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
  540. manager.responseSerializer = [AFHTTPResponseSerializer serializer];
  541. NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) {
  542. } completionHandler:completionBlock];
  543. return uploadTask;
  544. }
  545. #pragma mark - setter
  546. - (AFHTTPSessionManager *)manager {
  547. if (!_manager) {
  548. // 判断是否有请求基础url
  549. if ([self baseUrl].length) {
  550. _manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:[self baseUrl]]];
  551. } else {
  552. _manager = [AFHTTPSessionManager manager];
  553. }
  554. _manager.requestSerializer = [AFJSONRequestSerializer serializer];
  555. // _manager.responseSerializer = [AFJSONResponseSerializer serializer];
  556. _manager.responseSerializer = [AFHTTPResponseSerializer serializer];
  557. _manager.requestSerializer.stringEncoding = NSUTF8StringEncoding;
  558. //设置token
  559. [_manager.requestSerializer setValue:[UserManager token] forHTTPHeaderField:@"Authorization"];
  560. // 接收请求类型
  561. _manager.responseSerializer.acceptableContentTypes = [NSSet setWithArray:@[@"application/json",
  562. @"text/html",
  563. @"text/json",
  564. @"text/plain",
  565. @"text/javascript",
  566. @"text/xml",
  567. @"image/*"]];
  568. // 设置请求超时
  569. _manager.requestSerializer.timeoutInterval = 30.f;
  570. // 设置允许同时最大并发数量,过大容易出问题
  571. _manager.operationQueue.maxConcurrentOperationCount = 10;
  572. _manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
  573. _manager.securityPolicy.validatesDomainName = NO;
  574. _manager.securityPolicy.allowInvalidCertificates = YES;
  575. }
  576. return _manager;
  577. }
  578. - (NSString *)baseUrl {
  579. return BaseUrl;
  580. }
  581. - (void)cancelRequest
  582. {
  583. if ([_manager.tasks count] > 0) {
  584. NSLog(@"返回时取消网络请求");
  585. [_manager.tasks makeObjectsPerformSelector:@selector(cancel)];
  586. //NSLog(@"tasks = %@",manager.tasks);
  587. }
  588. }
  589. - (void)reLoginApp:(NSURLSessionDataTask *)task
  590. {
  591. NSHTTPURLResponse *response = (NSHTTPURLResponse*)task.response;
  592. NSInteger statusCode = response.statusCode;
  593. if (statusCode == 401) {
  594. [self changeToLogin];
  595. }
  596. }
  597. -(void)changeToLogin{
  598. [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"LOGINTOKEN"];
  599. [[NSUserDefaults standardUserDefaults] synchronize];
  600. [[EMClient sharedClient] logout:YES completion:^(EMError *aError) {
  601. [[HttpManager sharedHttpManager].manager.requestSerializer setValue:@"" forHTTPHeaderField:@"Authorization"];
  602. UIWindow *window = [UtilsTools getWindow];
  603. window.rootViewController = [StoryboardManager shared].login.instantiateInitialViewController;
  604. [window makeKeyAndVisible];
  605. }];
  606. }
  607. @end