HttpManager.m 29 KB

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