123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677 |
- //
- // 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<AFMultipartFormData> _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<AFMultipartFormData> _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<AFMultipartFormData> _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<NSDictionary<NSString*,id>*>*)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<AFMultipartFormData> formData) {
- for (int i=0; i<fileDatas.count; i++) {
- NSDictionary* unitData = fileDatas[i];
- if (unitData && [unitData objectForKey:@"key"] && [unitData objectForKey:@"filename"] && [unitData objectForKey:@"data"]) {
- if ([[unitData objectForKey:@"data"] isKindOfClass:[NSData class]]) {
- [formData appendPartWithFileData:(NSData*)[unitData objectForKey:@"data"] name:[unitData objectForKey:@"key"] fileName:[unitData objectForKey:@"filename"] mimeType:@"multipart/form-data"];
- }else if([[unitData objectForKey:@"data"] isKindOfClass:[NSURL class]]){
- [formData appendPartWithFileURL:(NSURL*)[unitData objectForKey:@"data"] name:[unitData objectForKey:@"key"] fileName:[unitData objectForKey:@"filename"] mimeType:@"multipart/form-data" error:nil];
- }
- }
- }
- } error:&error];
- NSLog(@"error %@",error);
- // 将 NSURLRequest 与 completionBlock 包装为 NSURLSessionUploadTask
- AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
- manager.responseSerializer = [AFHTTPResponseSerializer serializer];
- NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) {
- } completionHandler:completionBlock];
- return uploadTask;
- }
- #pragma mark - setter
- - (AFHTTPSessionManager *)manager {
- if (!_manager) {
- // 判断是否有请求基础url
- if ([self baseUrl].length) {
- _manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:[self baseUrl]]];
- } else {
- _manager = [AFHTTPSessionManager manager];
- }
- _manager.requestSerializer = [AFJSONRequestSerializer serializer];
- // _manager.responseSerializer = [AFJSONResponseSerializer serializer];
- _manager.responseSerializer = [AFHTTPResponseSerializer serializer];
- _manager.requestSerializer.stringEncoding = NSUTF8StringEncoding;
- //设置token
- [_manager.requestSerializer setValue:[UserManager token] forHTTPHeaderField:@"Authorization"];
- // 接收请求类型
- _manager.responseSerializer.acceptableContentTypes = [NSSet setWithArray:@[@"application/json",
- @"text/html",
- @"text/json",
- @"text/plain",
- @"text/javascript",
- @"text/xml",
- @"image/*"]];
- // 设置请求超时
- _manager.requestSerializer.timeoutInterval = 30.f;
-
- // 设置允许同时最大并发数量,过大容易出问题
- _manager.operationQueue.maxConcurrentOperationCount = 10;
-
- _manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
- _manager.securityPolicy.validatesDomainName = NO;
- _manager.securityPolicy.allowInvalidCertificates = YES;
-
- }
- return _manager;
- }
- - (NSString *)baseUrl {
- return BaseUrl;
- }
- - (void)cancelRequest
- {
- if ([_manager.tasks count] > 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
|