HTTP请求操作管理
AFHttpRequestOperationManager封装了通过HTTP与Web应用程序通信的一般模式,包括:请求创建、响应序列化、网络可达性监控和安全性,当然也包括HTTP请求操作管理。
GET请求
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager
manager];
[manager GET: @"http://example.com/resources.json" parameters: nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog( @"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog( @"Error: %@", error);
}];
[manager GET: @"http://example.com/resources.json" parameters: nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog( @"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog( @"Error: %@", error);
}];
POST网址形式编码的请求
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager
manager];
NSDictionary *parameters = @{ @"foo": @"bar"};
[manager POST: @"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog( @"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog( @"Error: %@", error);
}];
NSDictionary *parameters = @{ @"foo": @"bar"};
[manager POST: @"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog( @"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog( @"Error: %@", error);
}];
POST多表请求
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager
manager];
NSDictionary *parameters = @{ @"foo": @"bar"};
NSURL *filePath = [ NSURL fileURLWithPath: @"file://path/to/image.png"];
[manager POST: @"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^( id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:filePath name: @"image" error: nil];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog( @"Success: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog( @"Error: %@", error);
}];
NSDictionary *parameters = @{ @"foo": @"bar"};
NSURL *filePath = [ NSURL fileURLWithPath: @"file://path/to/image.png"];
[manager POST: @"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^( id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:filePath name: @"image" error: nil];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog( @"Success: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog( @"Error: %@", error);
}];
AFURLSessionManager
AFURLSessionManager 在一个规定的NSURLSessionConfiguration对象的基础上创建和管理一个NSURLSession对象,,并且遵从代理:
<NSURLSessionTaskDelegate>
,
<NSURLSessionDataDelegate>
,
<NSURLSessionDownloadDelegate>
, 和
<NSURLSessionDelegate>
创建一个上传任务
NSURLSessionConfiguration *configuration = [
NSURLSessionConfiguration
defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [ NSURL URLWithString: @"http://example.com/upload"];
NSURLRequest *request = [ NSURLRequest requestWithURL:URL];
NSURL *filePath = [ NSURL fileURLWithPath: @"file://path/to/image.png"];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress: nil completionHandler:^( NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog( @"Error: %@", error);
} else {
NSLog( @"Success: %@ %@", response, responseObject);
}
}];
[uploadTask resume];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [ NSURL URLWithString: @"http://example.com/upload"];
NSURLRequest *request = [ NSURLRequest requestWithURL:URL];
NSURL *filePath = [ NSURL fileURLWithPath: @"file://path/to/image.png"];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress: nil completionHandler:^( NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog( @"Error: %@", error);
} else {
NSLog( @"Success: %@ %@", response, responseObject);
}
}];
[uploadTask resume];
创建一个带多表和进度的上传任务
NSMutableURLRequest *request = [[AFHTTPRequestSerializer
serializer]
multipartFormRequestWithMethod:
@"POST"
URLString:
@"http://example.com/upload"
parameters:
nil
constructingBodyWithBlock:^(
id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:[ NSURL fileURLWithPath: @"file://path/to/image.jpg"] name: @"file" fileName: @"filename.jpg" mimeType: @"image/jpeg" error: nil];
} error: nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[ NSURLSessionConfiguration defaultSessionConfiguration]];
NSProgress *progress = nil;
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^( NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog( @"Error: %@", error);
} else {
NSLog( @"%@ %@", response, responseObject);
}
}];
[uploadTask resume];
[formData appendPartWithFileURL:[ NSURL fileURLWithPath: @"file://path/to/image.jpg"] name: @"file" fileName: @"filename.jpg" mimeType: @"image/jpeg" error: nil];
} error: nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[ NSURLSessionConfiguration defaultSessionConfiguration]];
NSProgress *progress = nil;
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^( NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog( @"Error: %@", error);
} else {
NSLog( @"%@ %@", response, responseObject);
}
}];
[uploadTask resume];
创建一个数据流Data任务
NSURLSessionConfiguration *configuration = [
NSURLSessionConfiguration
defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [ NSURL URLWithString: @"http://example.com/upload"];
NSURLRequest *request = [ NSURLRequest requestWithURL:URL];
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^( NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog( @"Error: %@", error);
} else {
NSLog( @"%@ %@", response, responseObject);
}
}];
[dataTask resume];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [ NSURL URLWithString: @"http://example.com/upload"];
NSURLRequest *request = [ NSURLRequest requestWithURL:URL];
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^( NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog( @"Error: %@", error);
} else {
NSLog( @"%@ %@", response, responseObject);
}
}];
[dataTask resume];
请求序列化
请求序列化是指创建以URL字符串、编码参数作为查询字符串或HTTP主题的请求。
NSString *URLString =
@"http://example.com";
NSDictionary *parameters = @{ @"foo": @"bar", @"baz": @[@ 1, @ 2, @ 3]};
NSDictionary *parameters = @{ @"foo": @"bar", @"baz": @[@ 1, @ 2, @ 3]};
查询字符串参数编码
[[AFHTTPRequestSerializer
serializer
]
requestWithMethod:
@" GET "
URLString:
URLString
parameters:
parameters
error:
nil
];
URL格式参数编码
[[AFHTTPRequestSerializer
serializer]
requestWithMethod:
@"POST"
URLString:URLString
parameters:parameters];
JSON参数编码
[[AFJSONRequestSerializer
serializer]
requestWithMethod:
@"POST"
URLString:URLString
parameters:parameters];
网络可达性管理
AFNetworkingReachabilityManager监控WWAN和WIFI网络的接口地址的可达性。
注意:
- 不要使用Reachability来确定原始请求是否应该发送(你应该尝试发送)
- 你可以使用Reachability来确定什么时候一个请求应该被自动重新尝试。(尽管请求仍旧可能失败,但是当一个Reachability发送连通性可用,是重新尝试一些请求的最佳时机。)
- 网络可达性是一个有用的工具,它可以确定为什么一个请求可能会失败。(当请求失败时,它告诉用户一些精确的错误)
共享Network Reachability
[[AFNetworkReachabilityManager
sharedManager]
setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
NSLog( @"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
}];
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
NSLog( @"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
}];
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
HTTP Manager Reachability
NSURL *baseURL = [
NSURL
URLWithString:
@"http://example.com/"];
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL];
NSOperationQueue *operationQueue = manager.operationQueue;
[manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusReachableViaWWAN:
case AFNetworkReachabilityStatusReachableViaWiFi:
[operationQueue setSuspended: NO];
break;
case AFNetworkReachabilityStatusNotReachable:
default:
[operationQueue setSuspended: YES];
break;
}
}];
[manager.reachabilityManager startMonitoring];
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL];
NSOperationQueue *operationQueue = manager.operationQueue;
[manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusReachableViaWWAN:
case AFNetworkReachabilityStatusReachableViaWiFi:
[operationQueue setSuspended: NO];
break;
case AFNetworkReachabilityStatusNotReachable:
default:
[operationQueue setSuspended: YES];
break;
}
}];
[manager.reachabilityManager startMonitoring];
安全策略
AFSecurityPolicy评估服务器对X.509证书和通过安全连接的公共秘钥是否信任。
增加固定的SSL证书到你的应用程序有助于防止人为攻击和其他安全漏洞。
应用程序处理敏感的客户数据或财务信息,我们强烈建议HTTPS连接配置和启用SSL。
允许无效的SSL证书
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager
manager];
manager.securityPolicy.allowInvalidCertificates =
YES;
// not recommended for production
AFHttpRequestOperation
AFHTTPRequestOperation是使用HTTP或HTTPS协议的AFURLConnectionOperation的子类。
它
封装获取的HTTP状态和类型来表示请求的成功与否。
虽然AFHTTPRequestOperationManager通常是提出请求的最佳方式,但是AFHTTPRequestOperation可以单独使用。
GET与AFHTTPRequestOperation
NSURL *URL = [
NSURL
URLWithString:
@"http://example.com/resources/123.json"];
NSURLRequest *request = [ NSURLRequest requestWithURL:URL];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFJSONResponseSerializer serializer];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog( @"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog( @"Error: %@", error);
}];
[[ NSOperationQueue mainQueue] addOperation:op];
NSURLRequest *request = [ NSURLRequest requestWithURL:URL];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFJSONResponseSerializer serializer];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog( @"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog( @"Error: %@", error);
}];
[[ NSOperationQueue mainQueue] addOperation:op];
批量多请求
NSMutableArray *mutableOperations = [
NSMutableArray
array];
for ( NSURL *fileURL in filesToUpload) {
NSURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod: @"POST" URLString: @"http://example.com/upload" parameters: nil constructingBodyWithBlock:^( id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:fileURL name: @"images[]" error: nil];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[mutableOperations addObject:operation];
}
NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:@[...] progressBlock:^( NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {
NSLog( @"%lu of %lu complete", numberOfFinishedOperations, totalNumberOfOperations);
} completionBlock:^( NSArray *operations) {
NSLog( @"All operations in batch complete");
}];
[[ NSOperationQueue mainQueue] addOperations:operations waitUntilFinished: NO];
for ( NSURL *fileURL in filesToUpload) {
NSURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod: @"POST" URLString: @"http://example.com/upload" parameters: nil constructingBodyWithBlock:^( id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:fileURL name: @"images[]" error: nil];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[mutableOperations addObject:operation];
}
NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:@[...] progressBlock:^( NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {
NSLog( @"%lu of %lu complete", numberOfFinishedOperations, totalNumberOfOperations);
} completionBlock:^( NSArray *operations) {
NSLog( @"All operations in batch complete");
}];
[[ NSOperationQueue mainQueue] addOperations:operations waitUntilFinished: NO];