当前位置:   article > 正文

iOS开发-AFNetworking网络请求及上传下载功能_afnetwork下载地址

afnetwork下载地址

iOS开发-AFNetworking网络请求及上传下载功能

AFNetworking是一个轻量级的iOS网络通信类库,可以方便实现网络请求。

一、使用AFNetworking

在Podfile中安装

pod 'AFNetworking'
  • 1

导入AFNetworking

#import "AFNetworking.h"
  • 1

AFNetworking下载地址:https://github.com/AFNetworking/AFNetworking

二、AFHTTPSessionManager

AFHTTPSessionManager提供了各种请求方式,并支持https格式。

AFHTTPSessionManager可以允许使用无效的SSL证书

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.securityPolicy.allowInvalidCertificates = YES; // 不建议用于生产环境
  • 1
  • 2

三、实现常用的请求封装设置

配置请求超时时间、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"]];
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

完整代码如下

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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86

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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • 261
  • 262
  • 263
  • 264
  • 265
  • 266
  • 267
  • 268
  • 269
  • 270
  • 271
  • 272
  • 273
  • 274
  • 275
  • 276
  • 277
  • 278
  • 279
  • 280
  • 281
  • 282
  • 283
  • 284
  • 285
  • 286
  • 287
  • 288
  • 289
  • 290
  • 291
  • 292
  • 293
  • 294
  • 295
  • 296
  • 297
  • 298

四、小结

AFNetworking是iOS、macOS、watchOS和tvOS的一个非常受欢迎的网络库。可以方便实现网络请求。

学习记录,每天不停进步。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/629895
推荐阅读
相关标签
  

闽ICP备14008679号