// // HttpManager.m // TheoryNetwork // // Created by tederen on 2019/9/25. // Copyright © 2019 tederen. All rights reserved. // #import "HttpManager.h" @interface HttpManager () @end @implementation HttpManager TDShareInstance_implementation(HttpManager) - (void)GET:(NSString *)URLString parameters:(nullable id)parameters success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure { [self.manager GET:URLString parameters:parameters progress:nil success:success failure:failure]; } - (void)POST:(NSString *)URLString parameters:(nullable id)parameters success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure { [self.manager POST:URLString parameters:parameters progress:nil success:success failure:failure]; } - (void)startRequestWithUrl:(NSString *)url method:(NSString *)method params:(NSDictionary *)params{ NSError *error; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error]; NSString *jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding]; AFURLSessionManager *manager = [[AFURLSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:method URLString:url parameters:nil error:nil]; request.timeoutInterval = 30; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; [request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; // manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/plain"]; [request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]]; [[manager dataTaskWithRequest:request uploadProgress:^(NSProgress * _Nonnull uploadProgress) { } downloadProgress:^(NSProgress * _Nonnull downloadProgress) { } completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { if (!error) { NSLog(@"Reply JOSN:%@",responseObject); }else{ NSLog(@"ERROR:%@,%@,%@",error,response,responseObject); } }] resume] ; } - (void)DeleteWithUrl:(NSString *)url parameters:(NSDictionary *)parameters success:(void (^)(id responseObject))successful failure:(void (^) (NSError *error))failure{ if (url.length==0) { return; } if (![url hasPrefix:@"http"]) { url = [BaseUrl stringByAppendingString:url]; } [self DeleteUrl:url parameters:parameters responseStyle:JOSN success:successful failure:failure]; } - (void)DeleteUrl:(NSString *)url parameters:(NSDictionary *)parameters success:(void (^)(id responseObject))successful failure:(void (^) (NSError *error))failure{ [self DeleteUrl:url parameters:parameters responseStyle:JOSN success:successful failure:failure]; } - (void)DeleteUrl:(NSString *)url parameters:(NSDictionary *)parameters responseStyle:(FWZRsponseStyle)style success:(void (^)(id responseObject))successful failure:(void (^) (NSError *error))failure { switch (style) { case JOSN:{ self.manager.responseSerializer = [AFJSONResponseSerializer serializer]; }break; case XML:{ self.manager.responseSerializer = [AFXMLParserResponseSerializer serializer]; }break; case DATA:{ self.manager.responseSerializer = [AFHTTPResponseSerializer serializer]; }break; } NSError *error = nil; //判断接口是否是空值 if (url.length == 0 || [url isEqualToString:@""]) { failure(error); } self.manager.requestSerializer.HTTPMethodsEncodingParametersInURI = [NSSet setWithObjects:@"GET", @"HEAD", nil]; //开始请求内容 [self.manager DELETE:url parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { [self reLoginApp:task]; successful(responseObject); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { [self reLoginApp:task]; failure(error); }]; } - (void)GETUrl:(NSString *)url parameters:(NSDictionary *)parameters success:(void (^)(id responseObject))successful failure:(void (^) (NSError *error))failure { [self GETUrl:url parameters:parameters responseStyle:JOSN success:successful failure:failure]; } - (void)GETUrl:(NSString *)url parameters:(NSDictionary *)parameters responseStyle:(FWZRsponseStyle)style success:(void (^)(id responseObject))successful failure:(void (^) (NSError *error))failure { switch (style) { case JOSN:{ self.manager.responseSerializer = [AFJSONResponseSerializer serializer]; }break; case XML:{ self.manager.responseSerializer = [AFXMLParserResponseSerializer serializer]; }break; case DATA:{ self.manager.responseSerializer = [AFHTTPResponseSerializer serializer]; }break; } NSError *error = nil; //判断接口是否是空值 if (url.length == 0 || [url isEqualToString:@""]) { failure(error); } //开始请求内容 [self.manager GET:url parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) { //如果需要填充进度内容,可以直接进行内容添加 } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { [self reLoginApp:task]; successful(responseObject); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { [self reLoginApp:task]; failure(error); }]; } /// 只需要传 api url 即可 - (void)GETWithUrl:(NSString *)url parameters:(NSDictionary *)parameters success:(void (^)(id responseObject))successful failure:(void (^) (NSError *error))failure{ if (url.length==0) { return; } if (![url hasPrefix:@"http"]) { url = [BaseUrl stringByAppendingString:url]; } [self GETUrl:url parameters:parameters responseStyle:JOSN success:successful failure:failure]; } /**  POST请求接口  */ /// 只需要传 api url 即可 - (void)POSTWithUrl:(NSString *)url parameters:(NSDictionary *)parameters success:(void (^)(id responseObject))successful failure:(void (^) (NSError *error))failure{ if (url.length==0) { return; } if (![url hasPrefix:@"http"]) { url = [BaseUrl stringByAppendingString:url]; } [self POSTUrl:url parameters:parameters responseStyle:JOSN success:successful failure:failure]; } //responseStyle:(responseStyle)style - (void)POSTUrl:(NSString *)url parameters:(NSDictionary *)parameters success:(void (^)(id responseObject))successful failure:(void (^) (NSError *error))failure { [self POSTUrl:url parameters:parameters responseStyle:DATA success:successful failure:failure]; } - (void)POSTUrl:(NSString *)url parameters:(NSDictionary *)parameters responseStyle:(FWZRsponseStyle)style success:(void (^)(id responseObject))successful failure:(void (^) (NSError *error))failure { switch (style) { case JOSN:{ self.manager.responseSerializer = [AFJSONResponseSerializer serializer]; }break; case XML:{ self.manager.responseSerializer = [AFXMLParserResponseSerializer serializer]; }break; case DATA:{ self.manager.responseSerializer = [AFHTTPResponseSerializer serializer]; }break; } NSError *error = nil; if (url.length == 0 || [url isEqualToString:@""]) { failure(error); } [self.manager POST:url parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) { } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { [self reLoginApp:task]; successful(responseObject); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { [self reLoginApp:task]; failure(error); }]; } /** 图片上传接口(上传音频与图片是一致的,需要更改的只是 mimeType类型,根据要求设置对应的格式即可) @param url 请求接口 @param paramters 请求参数 @param pictureData 图片数据 @param pictureKey 与后台约定的 文件key @param successful 成功返回 @param failure 失败返回 */ - (void)HeaderUploadUrl:(NSString *)url parameters:(NSDictionary *)paramters pictureData:(NSData *)pictureData pictureKey:(NSString *)pictureKey success:(void (^) (id responseObject))successful failure:(void (^) (NSError *error))failure { NSError *error = nil; //接口URL为空 if (url.length == 0 || [url isEqualToString:@""] ) { failure(error); } // //传入参数为空 // if ([ZYCTool isNullToDictionary:paramters]) { // failure(error); // } //传入上传图片数据为空(NSData) if (pictureData.length == 0) { failure(error); } //上传图片,服务器端文件名 if (pictureKey.length == 0 || [pictureKey isEqualToString:@""]) { failure(error); } [self.manager POST:url parameters:paramters constructingBodyWithBlock:^(id _Nonnull formData) { //对上传完文件的配置 //获取当前时间(int 时间戳转换) int nowDate = [[NSString stringWithFormat:@"%ld",(long)[[NSDate date] timeIntervalSince1970]]intValue]; NSString *fileName = [NSString stringWithFormat:@"%d.jpg",nowDate]; //参数介绍 //fileData : 图片资源 name : 预定key fileName : 文件名 mimeType : 资源类型(根据后台进行对应配置) [formData appendPartWithFileData:pictureData name:pictureKey fileName:fileName mimeType:@"image/jpeg"]; } progress:^(NSProgress * _Nonnull uploadProgress) { //上传进度 dispatch_sync(dispatch_get_main_queue(), ^{ // progress ? progress(uploadProgress) : nil; }); } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { successful(responseObject); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { //可以将http响应码返回,以便于判断错误 failure(error); }]; } /** 图片上传接口(上传音频与图片是一致的,需要更改的只是 mimeType类型,根据要求设置对应的格式即可) @param url 请求接口 @param paramters 请求参数 @param array 图片数组 @param pictureKey 与后台约定的 文件key @param successful 成功返回 @param failure 失败返回 */ - (void)HeaderUploadUrl:(NSString *)url parameters:(NSDictionary *)paramters pictureArray:(NSArray *)array pictureKey:(NSString *)pictureKey success:(void (^) (id responseObject))successful failure:(void (^) (NSError *error))failure { NSError *error = nil; //接口URL为空 if (url.length == 0 || [url isEqualToString:@""] ) { failure(error); } // //传入参数为空 // if ([ZYCTool isNullToDictionary:paramters]) { // failure(error); // } //传入上传图片数据为空(NSData) if (array.count == 0) { failure(error); } //上传图片,服务器端文件名 if (pictureKey.length == 0 || [pictureKey isEqualToString:@""]) { failure(error); } [self.manager POST:url parameters:paramters constructingBodyWithBlock:^(id _Nonnull formData) { //对上传完文件的配置 //获取当前时间(int 时间戳转换) for (NSInteger i = 0; i < array.count; i++) { int nowDate = [[NSString stringWithFormat:@"%ld",(long)[[NSDate date] timeIntervalSince1970]]intValue]; NSString *fileName = [NSString stringWithFormat:@"%d%ld.jpg",nowDate,(long)i]; //参数介绍 //fileData : 图片资源 name : 预定key fileName : 文件名 mimeType : 资源类型(根据后台进行对应配置) [formData appendPartWithFileData:array[i] name:pictureKey fileName:fileName mimeType:@"image/jpeg"]; } } progress:^(NSProgress * _Nonnull uploadProgress) { //上传进度 dispatch_sync(dispatch_get_main_queue(), ^{ // progress ? progress(uploadProgress) : nil; }); } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { [self reLoginApp:task]; successful(responseObject); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { [self reLoginApp:task]; //可以将http响应码返回,以便于判断错误 failure(error); }]; } - (void)HeaderUploadFileUrl:(NSString *)url parameters:(NSDictionary *)paramters fileData:(NSData *)fileData fileKey:(NSString *)fileKey fileName:(NSString *)fileName mimeType:(NSString *)mimeType success:(void (^) (id responseObject))successful failure:(void (^) (NSError *error))failure { NSError *error = nil; //接口URL为空 if (url.length == 0 || [url isEqualToString:@""] ) { failure(error); } //传入上传图片数据为空(NSData) if (fileData.length == 0) { failure(error); } //上传图片,服务器端文件名 if (fileKey.length == 0 || [fileKey isEqualToString:@""]) { failure(error); } self.manager.responseSerializer = [AFJSONResponseSerializer serializer]; [self.manager POST:url parameters:paramters constructingBodyWithBlock:^(id _Nonnull formData) { //fileData : 图片资源 name : 预定key fileName : 文件名 mimeType : 资源类型(根据后台进行对应配置) [formData appendPartWithFileData:fileData name:fileKey fileName:fileName mimeType:mimeType]; } progress:^(NSProgress * _Nonnull uploadProgress) { //上传进度 dispatch_sync(dispatch_get_main_queue(), ^{ // progress ? progress(uploadProgress) : nil; }); } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { [self reLoginApp:task]; successful(responseObject); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { [self reLoginApp:task]; //可以将http响应码返回,以便于判断错误 failure(error); }]; } // // ///** // 下载文件接口 // // @param url 请求接口 // @param progress 下载进度 // @param downloadFilePath 文件保存路径 // @param successful  返回路径内容 // @param failure 失败返回 // */ //- (void)downloadUrl:(NSString *)url //           progress:(HttpProgress)progress //   downloadFilePath:(NSString *)downloadFilePath //            success:(void (^) (id responseObject))successful //            failure:(void (^) (NSError *error, ParamtersJudgeCode  judgeCode))failure; // // // ///** // 下载文件接口 // @param url 请求接口 // @param progress 下载进度 // @param downloadFilePath 文件保存路径 // @param successful  返回路径内容 // @param failure 失败返回 // */ //- (void)downloadUrl:(NSString *)url //        progress:(HttpProgress)progress //        downloadFilePath:(NSString *)downloadFilePath //        success:(void (^) (id responseObject))successful //        failure:(void (^) (NSError *error, ParamtersJudgeCode  judgeCode))failure //  { //    //下载地址 //    NSURL *downloadURL = [NSURL URLWithString:url]; //    //设置请求 //    NSURLRequest *request = [NSURLRequest requestWithURL:downloadURL]; //    //下载操作 //    [_sessionManager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) { //        //下载进度 //        dispatch_sync(dispatch_get_main_queue(), ^{ //            progress ? progress(downloadProgress) : nil; //        }); // //    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) { //        //拼接缓存目录 //        NSString *downloadPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadFilePath ? downloadFilePath : @"Download"]; //        //打开文件管理器 //        NSFileManager *fileManager = [NSFileManager defaultManager]; //        //创建Download目录 //        [fileManager createDirectoryAtPath:downloadPath withIntermediateDirectories:YES attributes:nil error:nil]; //        //拼接文件路径 //        NSString *filePath = [downloadPath stringByAppendingPathComponent:response.suggestedFilename]; //        //返回文件位置的URL路径 //        return [NSURL fileURLWithPath:filePath]; //    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) { //        NSInteger responseCode = [self showResponseCode:response]; //        if (responseCode != 200) { //            successful ? successful(filePath.absoluteString): nil; //        }else { //            failure(error, UploadFailed); //        } //    }]; //} // - (void)downloadUrl:(NSString *)url downloadFilePath:(NSString *)downloadFilePath success:(void (^) (id responseObject))successful failure:(void (^) (NSError *error))failure { //下载地址 NSURL *downloadURL = [NSURL URLWithString:url]; //设置请求 NSURLRequest *request = [NSURLRequest requestWithURL:downloadURL]; //下载操作 [_manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) { } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) { //拼接缓存目录 NSString *downloadPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadFilePath ? downloadFilePath : @"Download"]; //打开文件管理器 NSFileManager *fileManager = [NSFileManager defaultManager]; //创建Download目录 [fileManager createDirectoryAtPath:downloadPath withIntermediateDirectories:YES attributes:nil error:nil]; //拼接文件路径 NSString *filePath = [downloadPath stringByAppendingPathComponent:response.suggestedFilename]; //返回文件位置的URL路径 return [NSURL fileURLWithPath:filePath]; } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) { failure(error); }]; } // // ///** // POST请求接口 // */ // // //- (void)POSTUrl:(NSString *)url parameters:(NSDictionary *)parameters success:(void (^)(id responseObject))successful //failure:(void (^) (NSError *error))failure //{ // NSError *error = nil; // if (url.length == 0 || [url isEqualToString:@""]) { // failure(error); // } // [self.manager POST:url parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) { // // } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { // successful(responseObject); // // } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { // failure(error); // }]; // //} - (void)PUTUrl:(NSString *)url parameters:(NSDictionary *)parameters success:(void (^)(id responseObject))successful failure:(void (^) (NSError *error))failure{ self.manager.responseSerializer = [AFHTTPResponseSerializer serializer]; NSError *error = nil; if (url.length == 0 || [url isEqualToString:@""]) { failure(error); } NSLog(@"url:%@",url); [self.manager PUT:url parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { [self reLoginApp:task]; successful(responseObject); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { [self reLoginApp:task]; failure(error); }]; } - (void)PUTUrl:(NSString *)url parameters:(NSDictionary *)parameters responseStyle:(FWZRsponseStyle)style success:(void (^)(id responseObject))successful failure:(void (^) (NSError *error))failure { switch (style) { case JOSN:{ self.manager.responseSerializer = [AFJSONResponseSerializer serializer]; }break; case XML:{ self.manager.responseSerializer = [AFXMLParserResponseSerializer serializer]; }break; case DATA:{ self.manager.responseSerializer = [AFHTTPResponseSerializer serializer]; }break; } NSError *error = nil; if (url.length == 0 || [url isEqualToString:@""]) { failure(error); } [self.manager PUT:url parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { [self reLoginApp:task]; successful(responseObject); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { [self reLoginApp:task]; failure(error); }]; } +(NSURLSessionUploadTask*)uploadTaskUrl:(NSURL*)uploadPage params:(NSDictionary*)params files:(NSArray*>*)fileDatas completion:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionBlock { NSLog(@"url %@\nparam %@",uploadPage,params); NSError* error = NULL; NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:[uploadPage absoluteString] parameters:params constructingBodyWithBlock:^(id formData) { for (int i=0; i 0) { NSLog(@"返回时取消网络请求"); [_manager.tasks makeObjectsPerformSelector:@selector(cancel)]; //NSLog(@"tasks = %@",manager.tasks); } } - (void)reLoginApp:(NSURLSessionDataTask *)task { NSHTTPURLResponse *response = (NSHTTPURLResponse*)task.response; NSInteger statusCode = response.statusCode; if (statusCode == 401) { [self changeToLogin]; } } -(void)changeToLogin{ [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"LOGINTOKEN"]; [[NSUserDefaults standardUserDefaults] synchronize]; [[EMClient sharedClient] logout:YES completion:^(EMError *aError) { [[HttpManager sharedHttpManager].manager.requestSerializer setValue:@"" forHTTPHeaderField:@"Authorization"]; UIWindow *window = [UtilsTools getWindow]; window.rootViewController = [StoryboardManager shared].login.instantiateInitialViewController; [window makeKeyAndVisible]; }]; } @end