iOS开发-AFNetworking网络请求及上传下载功能
AFNetworking是一个轻量级的iOS网络通信类库,可以方便实现网络请求。
在Podfile中安装
pod 'AFNetworking'
导入AFNetworking
#import "AFNetworking.h"
AFNetworking下载地址:https://github.com/AFNetworking/AFNetworking
AFHTTPSessionManager提供了各种请求方式,并支持https格式。
AFHTTPSessionManager可以允许使用无效的SSL证书
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.securityPolicy.allowInvalidCertificates = YES; // 不建议用于生产环境
配置请求超时时间、Content-Type、acceptableContentTypes
_httpManager = [[AFHTTPSessionManager alloc] init];
_httpManager.operationQueue.maxConcurrentOperationCount = 6;
_httpManager.requestSerializer = [AFJSONRequestSerializer serializer];
[_httpManager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
[_httpManager.requestSerializer setTimeoutInterval:10];
[_httpManager.requestSerializer setStringEncoding:NSUTF8StringEncoding];
_httpManager.responseSerializer = [AFJSONResponseSerializer serializer];
// [_manager.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
[_httpManager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
_httpManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"multipart/form-data", @"application/json", @"text/html", @"image/jpeg", @"image/png", @"application/octet-stream", @"text/json", @"text/javascript", @"text/html", nil];
_httpManager.requestSerializer.HTTPMethodsEncodingParametersInURI = [NSSet setWithArray:@[@"POST", @"GET", @"HEAD", @"PUT", @"DELETE"]];
完整代码如下
INHttpClientUtil.h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import "INHttpUrlDefine.h"
typedef NS_ENUM(NSInteger, HttpClientType) {
HttpClientTypeDefault, //默认
HttpClientTypeMob, //mob提供的天气等服务
HttpClientTypeHeWeather, //和风天气提供的天气等服务
HttpClientTypeWithOut, //mob提供的天气等服务
} ;
typedef NS_ENUM(NSInteger, UploadMimeType) {
UploadMimeTypeDefault, //默认
UploadMimeTypeImage, //图片
UploadMimeTypeAudio, //音频
UploadMimeTypeVideo, //视频
} ;
typedef NS_ENUM(NSInteger, HttpErrorType) {
HttpErrorTypeDefault = 0, //默认
HttpErrorTypeNetWork, //网络出错
HttpErrorTypeTimeout, //请求超时
HttpErrorTypeNotFound, //404资源不存在
HttpErrorTypeBadRequest, //非法请求
HttpErrorTypeForbidRequest, //禁止访问
HttpErrorTypeAuth, //认证失败
HttpErrorTypeServerDown, //服务器出错
//自定义错误码
HttpErrorTypeNotLogin, //未登录,无法获取资源
HttpErrorTypeJsonParse, //数据解析失败
} ;
@interface HttpError : NSObject
@property (nonatomic, assign) HttpErrorType etype;
@property (nonatomic, strong) NSString *message;
@end
@interface INHttpClientUtil : NSObject
+ (instancetype)sharedInstance;
- (void)getWithClientType:(HttpClientType)type
url:(NSString *)url
params:(NSDictionary *)params
success:(void(^)(id responseObj))success
failure:(void(^)(HttpError * e))failure;
- (void)postWithClientType:(HttpClientType)type
url:(NSString *)url
params:(NSDictionary *)params
success:(void(^)(id responseObj))success
failure:(void(^)(HttpError * e))failure;
- (void)uploadWithClientType:(HttpClientType)type
mimeType:(UploadMimeType)mimeType
url:(NSString *)url
filePath:(NSString *)filePath
params:(NSDictionary *)params
progress:(void(^)(NSProgress *uploadProgress))progress
success:(void(^)(id responseObj))success
failure:(void(^)(HttpError * e))failure;
/**
请求下载
@param aUrl aurl
@param aSavePath aSavePath
@param aFileName aFileName
@param aTag aTag
@param downloadprogress downloadprogress
@param success success
@param failure failure
*/
- (void)downloadFileURL:(NSString *)aUrl
savePath:(NSString *)aSavePath
fileName:(NSString *)aFileName
tag:(NSInteger)aTag
downloadProgress:(void(^)(CGFloat progress))downloadprogress
success:(void(^)(NSURLResponse *response,NSString *filePath))success
failure:(void(^)(HttpError * e))failure;
@end
INHttpClientUtil.m
#import "INHttpClientUtil.h"
#import "AFNetworking.h"
#import "SDSessionDbManager.h"
@implementation HttpError
@end
@interface INHttpClientUtil ()
@property (nonatomic, strong) AFHTTPSessionManager *httpManager;
@end
@implementation INHttpClientUtil
+ (instancetype)sharedInstance {
static INHttpClientUtil *_sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedInstance = [[INHttpClientUtil alloc] init];
_sharedInstance.httpManager = [AFHTTPSessionManager manager];
_sharedInstance.httpManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", nil];
});
return _sharedInstance;
}
- (AFHTTPSessionManager *)httpManager{
if (!_httpManager) {
_httpManager = [[AFHTTPSessionManager alloc] init];
_httpManager.operationQueue.maxConcurrentOperationCount = 6;
_httpManager.requestSerializer = [AFJSONRequestSerializer serializer];
[_httpManager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
[_httpManager.requestSerializer setTimeoutInterval:10];
[_httpManager.requestSerializer setStringEncoding:NSUTF8StringEncoding];
_httpManager.responseSerializer = [AFJSONResponseSerializer serializer];
// [_manager.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
[_httpManager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
_httpManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"multipart/form-data", @"application/json", @"text/html", @"image/jpeg", @"image/png", @"application/octet-stream", @"text/json", @"text/javascript", @"text/html", nil];
_httpManager.requestSerializer.HTTPMethodsEncodingParametersInURI = [NSSet setWithArray:@[@"POST", @"GET", @"HEAD", @"PUT", @"DELETE"]];
}
NSString *curAuthId = [SDSessionManager shareInstance].authId;
[_httpManager.requestSerializer setValue:curAuthId forHTTPHeaderField:@"authId"];
NSString *curUserId = [SDSessionManager shareInstance].userId;
[_httpManager.requestSerializer setValue:curUserId forHTTPHeaderField:@"currentUserId"];
NSString *uuidStr = [[NSUUID UUID] UUIDString];
[_httpManager.requestSerializer setValue:uuidStr forHTTPHeaderField:@"deviceId"];
NSString *platform = @"iOS";
[_httpManager.requestSerializer setValue:platform forHTTPHeaderField:@"platform"];
NSString *clientos = @"1";
//登录的来源系统: 0 未知 1 ios 2 android 3 web
[_httpManager.requestSerializer setValue:clientos forHTTPHeaderField:@"clientos"];
NSString *ts = [NSString stringWithFormat:@"%lld",(long long)(([[NSDate date] timeIntervalSince1970]*1000)/1000)];
[_httpManager.requestSerializer setValue:ts forHTTPHeaderField:@"ts"];
//设置请求头
NSString *token = [SDSessionManager shareInstance].userToken;
[_httpManager.requestSerializer setValue:token forHTTPHeaderField:@"token"];
//设置请求头
//NSString *token = [SDSessionManager shareInstance].token;
[_httpManager.requestSerializer setValue:token forHTTPHeaderField:@"sign"];
//app版本号
NSString *appVersion = [ [[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
[_httpManager.requestSerializer setValue:appVersion forHTTPHeaderField:@"versionCode"];
return _httpManager;
}
#pragma mark - Http Request Failure
- (HttpError *)httpRequestFailure:(NSHTTPURLResponse *)response
error:(NSError *)error {
HttpError *e = [[HttpError alloc] init];
if(error.code == NSURLErrorNotConnectedToInternet || error.code == NSURLErrorCannotFindHost || error.code == NSURLErrorCannotConnectToHost){
e.etype = HttpErrorTypeNetWork;
e.message = @"网络连接失败!";
return e;
}
if (error.code == NSURLErrorTimedOut){
e.etype = HttpErrorTypeTimeout;
e.message = @"网路连接超时!";
return e;
}
NSInteger statusCode = response.statusCode;
if (statusCode == 401) {
e.etype = HttpErrorTypeAuth;
e.message = @"认证失败";
} else if (statusCode == 400){
e.etype = HttpErrorTypeBadRequest;
e.message = @"无效请求";
} else if (statusCode == 404) {
e.etype = HttpErrorTypeNotFound;
e.message = @"访问的资源丢失了!";
} else if (statusCode >= 500){
e.etype = HttpErrorTypeServerDown;
e.message = @"服务器居然累倒了!";
}
return e;
}
#pragma mark - Http Get
- (void)getWithClientType:(HttpClientType)type
url:(NSString *)url
params:(NSDictionary *)params
success:(void(^)(id responseObj))success
failure:(void(^)(HttpError * e))failure {
NSString *requestUrl = [self requestUrlWithPath:url clientType:type];
[self setHttpRequestCookie];
[self.httpManager GET:requestUrl parameters:params progress:^(NSProgress *downloadProgress) {
//获取进度
} success:^(NSURLSessionDataTask *task, id responseObject) {
//成功
[self cookieHttpResponse:task url:url];
success(responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
//失败
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)task.response;
HttpError *e = [self httpRequestFailure:httpResponse error:error];
failure(e);
}];
}
#pragma mark - Http post
- (void)postWithClientType:(HttpClientType)type
url:(NSString *)url
params:(NSDictionary *)params
success:(void(^)(id responseObj))success
failure:(void(^)(HttpError * e))failure {
NSString *requestUrl = [self requestUrlWithPath:url clientType:type];
[self setHttpRequestCookie];
[self.httpManager POST:requestUrl parameters:params progress:^(NSProgress *uploadProgress) {
//获取进度
} success:^(NSURLSessionDataTask *task, id responseObject) {
//成功
[self cookieHttpResponse:task url:url];
success(responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
//失败
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)task.response;
HttpError *e = [self httpRequestFailure:httpResponse error:error];
failure(e);
}];
}
#pragma mark - Http upload
- (void)uploadWithClientType:(HttpClientType)type
mimeType:(UploadMimeType)mimeType
url:(NSString *)url
filePath:(NSString *)filePath
params:(NSDictionary *)params
progress:(void(^)(NSProgress *uploadProgress))progress
success:(void(^)(id responseObj))success
failure:(void(^)(HttpError * e))failure {
NSString *requestUrl = [self requestUrlWithPath:url clientType:type];
[self setHttpRequestCookie];
[self.httpManager POST:requestUrl parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
if (mimeType == UploadMimeTypeImage) {
NSData *data = [NSData dataWithContentsOfFile:filePath];
[formData appendPartWithFileData:data name:@"file" fileName:@"file" mimeType:@"image/jpeg"];
} else if (mimeType == UploadMimeTypeAudio) {
[formData appendPartWithFileURL:[NSURL fileURLWithPath:filePath] name:@"file" fileName:@"file" mimeType:@"audio/amr" error:nil];
} else if (mimeType == UploadMimeTypeVideo) {
[formData appendPartWithFileURL:[NSURL fileURLWithPath:filePath] name:@"file" fileName:@"file" mimeType:@"video/avi" error:nil];
}
} progress:^(NSProgress *uploadProgress) {
//打印下上传进度
DLog(@"%lf",1.0 *uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
progress(uploadProgress);
} success:^(NSURLSessionDataTask *task, id responseObject) {
//请求成功
success(responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
//请求失败
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)task.response;
HttpError *e = [self httpRequestFailure:httpResponse error:error];
failure(e);
}];
}
#pragma mark - Http download
/**
请求下载
@param aUrl aurl
@param aSavePath aSavePath
@param aFileName aFileName
@param aTag aTag
@param downloadprogress downloadprogress
@param success success
@param failure failure
*/
- (void)downloadFileURL:(NSString *)aUrl
savePath:(NSString *)aSavePath
fileName:(NSString *)aFileName
tag:(NSInteger)aTag
downloadProgress:(void(^)(CGFloat progress))downloadprogress
success:(void(^)(NSURLResponse *response,NSString *filePath))success
failure:(void(^)(HttpError * e))failure {
NSFileManager *fileManger = [NSFileManager defaultManager];
if ([fileManger fileExistsAtPath:[aSavePath stringByAppendingPathComponent:aFileName]]) {
//文件存在
return;
}
//2.确定请求的URL地址
NSString *requestUrl = [self requestUrlWithPath:aUrl clientType:HttpClientTypeWithOut];
NSMutableURLRequest *request = [self.httpManager.requestSerializer requestWithMethod:@"GET" URLString:requestUrl parameters:nil error:nil];
__block NSURLSessionDownloadTask *downloadTask = nil;
downloadTask = [self.httpManager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
dispatch_async(dispatch_get_main_queue(), ^{
downloadprogress(1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
});
} destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
return [NSURL fileURLWithPath:aSavePath];
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
if(error == nil) {
success(response,[filePath path]);
} else {
//下载失败
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
HttpError *e = [self httpRequestFailure:httpResponse error:error];
failure(e);
}
}];
[downloadTask resume];
}
#pragma mark - Http Request Url
- (NSString *)requestUrlWithPath:(NSString *)path clientType:(HttpClientType)type {
NSString *url = path;
if (type == HttpClientTypeDefault) {
url = [NSString stringWithFormat:@"%@%@", kHttpHostUrl, path];
} else if (type == HttpClientTypeMob) {
url = [NSString stringWithFormat:@"%@%@",kHttpMobUrl, path];
} else if (type == HttpClientTypeHeWeather) {
url = [NSString stringWithFormat:@"%@%@",kHttpHeWeatherUrl, path];
}
return url;
}
- (NSSet *)contentTypes {
return [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html",@"text/plain", nil];
}
#pragma mark - GET Http Request Cookie
- (void)cookieHttpResponse:(NSURLSessionDataTask *)task url:(NSString *)url {
// 获取所有数据报头信息
NSHTTPURLResponse *HTTPResponse = (NSHTTPURLResponse *)task.response;
NSDictionary *fields = [HTTPResponse allHeaderFields];// 原生NSURLConnection写法
// 获取cookie方法
NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:fields forURL:[NSURL URLWithString:url]];
DLog(@"cookies:%@",cookies);
NSDictionary *requestFields=[NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
NSString *theNewCookie = [requestFields objectForKey:@"Cookie"];
if(theNewCookie.length > 0 && [theNewCookie containsString:@"JJD_TOKEN"]){
//服务器端将视情形返回cookie, 如果返回, 则保存;
[SDSessionManager shareInstance].userToken = theNewCookie;
[[SDSessionDbManager shareInstance] saveSessionInfoToDb:[SDSessionManager shareInstance]];
}
}
- (void)setHttpRequestCookie {
[self.httpManager.requestSerializer setHTTPShouldHandleCookies:YES];
[self.httpManager.requestSerializer setValue:[SDSessionManager shareInstance].userToken forHTTPHeaderField:@"Cookie"];
}
@end
AFNetworking是iOS、macOS、watchOS和tvOS的一个非常受欢迎的网络库。可以方便实现网络请求。
学习记录,每天不停进步。