AFNetworking是一个令人喜欢的网络类,对于iOS and Mac OS X,是在Foundation URL Loading System之上建立的,扩展的,功能强大的,高级的网络抽象类,它具有精心设计的模型框架,特征丰富的APIs,使你能很好的利用它。
或许最重要的特征是它令人惊讶的每天使用,并为她做贡献的开发者组成的团体,AFNetworking用在了一些最受欢迎,最流行的 iPhone, iPad,和Mac apps上。
选择AFNetworking用在你的下一个工程中,或者移植到你现有的工程,你将非常高兴使用它。
结构:
NSURLConnectio
AFURLConnectionOperation
AFHTTPRequestOperation
AFHTTPRequestOperationManager
NSURLSession (iOS 7 / Mac OS X 10.9)
AFURLSessionManager
AFHTTPSessionManager
Serialization
<AFURLRequestSerialization>
AFHTTPRequestSerializer
AFJSONRequestSerializer
AFPropertyListRequestSerializer
<AFURLResponseSerialization>
AFHTTPResponseSerializer
AFJSONResponseSerializer
AFXMLParserResponseSerializer
AFXMLDocumentResponseSerializer
(Mac OS X)AFPropertyListResponseSerializer
AFImageResponseSerializer
AFCompoundResponseSerializer
Additional Functionality
AFSecurityPolicy
AFNetworkReachabilityManager
用法:
HTTP Request Operation Manager
1.使用HTTPRequestOperationManager 进行GET请求
-(void)getRequest{
AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
// manager.responseSerializer = [AFJSONResponseSerializer serializer];
NSDictionary * parameters = @{@"format":@"json"};
[manager GET:@"http://c.m.163.com/nc/ad/headline/0-8.html" parameters:parameters success:^(AFHTTPRequestOperation * operation, id responseObject) {
NSLog(@"JSON:%@",responseObject);
} failure:^(AFHTTPRequestOperation * operation, NSError * error) {
NSLog(@"error :%@",[error localizedDescription]);
}];
}
2.使用HTTPRequestOperationManager 进行POST请求
-(void)PostRequest{
AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
// manager.requestSerializer = [AFHTTPRequestSerializer serializer];
// manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSDictionary * paramaters = @{@"username":@"xiaoxin",@"pwd":@"123456",@"name":@"小新"};
[manager POST:@"http://192.168.2.103:8080/st2/user/register.json" parameters:paramaters success:^(AFHTTPRequestOperation * operation, id responseObject) {
NSLog(@"%d",[NSThread isMainThread]);
NSLog(@"%@",responseObject);
} failure:^(AFHTTPRequestOperation * operation, NSError * error) {
NSLog(@"error :%@",[error localizedDescription]);
}];
}
3.使用HTTPRequestOperationManager 进行(多部分)POST请求
-(void)multiPostRequest{
AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
// NSDictionary * parametar = @{};
NSString * pathString =[[NSBundle mainBundle]pathForResource:@"a" ofType:@"pdf"];
NSURL * filePath = [NSURL fileURLWithPath:pathString];
[manager POST:@"http://192.168.2.103:8080/st2/question/submitQuestion.json" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:filePath name:@"textData" error:nil];
} success:^(AFHTTPRequestOperation * operation, id requestObject) {
NSLog(@"%@",requestObject);
} failure:^(AFHTTPRequestOperation * operation, NSError * error) {
NSLog(@"%@",[error localizedDescription]);
}];
}
AFURLSessionManager
1.创建一个下载队列
-(void)createDownloadTask{
NSURLSessionConfiguration * configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager * manager = [[AFURLSessionManager alloc]initWithSessionConfiguration:configuration];
//创建请求
NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://img.dwstatic.com/d3/1505/296762765078/1432813803695.jpg"]];
//创建下载队列
NSURLSessionDownloadTask * downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^ NSURL*(NSURL * targetPath, NSURLResponse * response) {
//下载存储路径
NSURL* documentDirectoryURL = [[NSFileManager defaultManager]URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
NSLog(@"%@",[documentDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]]);
return [documentDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse * response, NSURL * filePath, NSError * error) {
NSLog(@"file Download to :%@",filePath);
}];
[downloadTask resume];
}
2.创建一个上传队列
-(void)createUploadTask{
AFURLSessionManager * manager = [[AFURLSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://192.168.2.103:8080/st2/question/submitQuestion.json"]];
//要上传的本地文件路径
NSString * string = [[NSBundle mainBundle]pathForResource:@"a" ofType:@"pdf"];
NSURL * upLoadURL = [NSURL fileURLWithPath:string];
//创建上传对象
NSURLSessionUploadTask * upLoadTask = [manager uploadTaskWithRequest:request fromFile:upLoadURL progress:nil completionHandler:^(NSURLResponse * responseURL, id responseObject, NSError * error) {
if (error) {
NSLog(@"error :%@",error);
}else{
NSLog(@"sucess:%@,responseObject:%@",responseURL,responseObject);
}
}];
[upLoadTask resume];
}
3.创建一个上传任务,为多个请求
-(void)createUpLoadTaskForMultiRequest{
NSMutableURLRequest * request = [[AFHTTPRequestSerializer serializer]multipartFormRequestWithMethod:@"POST" URLString:@"http://192.168.2.103:8080/st2/question/submitQuestion.json" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//要上传文件路径
NSString * string = [[NSBundle mainBundle]pathForResource:@"a"ofType:@"pdf"];
NSURL * URLString = [NSURL fileURLWithPath:string];
[formData appendPartWithFileURL:URLString name:@"file" fileName:@"fileNmae.jpg" mimeType:@"image/jpeg" error:nil];
} error:nil];
AFURLSessionManager * manager = [[AFURLSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask * upLoadTask = [manager uploadTaskWithStreamedRequest:request progress:nil completionHandler:^(NSURLResponse * responseURL, id responseObject, NSError * error) {
if (error) {
NSLog(@"error :%@",error);
}else{
NSLog(@"sucess.....");
}
}];
[upLoadTask resume];
}
4.创建一个data task
-(void)createDataTask{
AFURLSessionManager * manager = [[AFURLSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLRequest * request =[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://192.168.2.103:8080/st2/question/submitQuestion.json"]];
NSURLSessionDataTask * dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * responseURL, id responseObject, NSError * error) {
if (error) {
NSLog(@"error :%@",[error localizedDescription]);
}else{
NSLog(@"sucess.....");
}
}];
[dataTask resume];
}
Request Serialization
请求器创建请求从URLString,编码参数parameters作为查询字符串或者HTTP body
NSString *URLString = @"http://example.com"; NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]};
Query String Parameter Encoding
[[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil];
GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3
URL Form Parameter Encoding
[[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters];
POST http://example.com/
Content-Type: application/x-www-form-urlencoded
foo=bar&baz[]=1&baz[]=2&baz[]=3
JSON Parameter Encoding
[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters];
POST http://example.com/
Content-Type: application/json
{"foo": "bar", "baz": [1,2,3]}
Network Reachability Manager
Network Reachability Manager 网络状态管理
/*
AFNetworkReachabilityManager监控网络的状态,提供WWAN和Wifi的网络接口
1.不要使用Reachability来决定初始的请求是否应该发送
你应该自己发送请求
2.你可以使用Reachability来决定一个请求应该被从新发送
即使请求仍然失败,Reachability notification that the connectivity is available is a good time to retry something.
3.网络状态是一个有用的工具来决定为什么一个请求会失败
一个网络请求失败以后,告诉用户处于脱机状态better than giving them a more technical but accurate error, such as "request timed out."
*/
-(void)SharedNetworkReachability{
[[AFNetworkReachabilityManager sharedManager]setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
[[AFNetworkReachabilityManager sharedManager]startMonitoring];
}];
}
//HTTP Manager Reachability
-(void)HTTPManagerReachability{
NSURL * baseURL = [NSURL URLWithString:@"http://192.168.2.103:8080/st2/question/submitQuestion.json"];
AFHTTPRequestOperationManager * manager = [[AFHTTPRequestOperationManager alloc]initWithBaseURL:baseURL];
NSOperationQueue * operation = manager.operationQueue;
[manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusReachableViaWWAN:
case AFNetworkReachabilityStatusReachableViaWiFi:
[operation setSuspended:NO];
break;
case AFNetworkReachabilityStatusNotReachable:
default:
[operation setSuspended:YES];
break;
}
}];
[manager.reachabilityManager startMonitoring];
}
AFHTTPRequestOperation
AFHTTPRequestOperation是AFURLConnectionOperation的子类使用HTTP或HTTPS协议进行请求,封装了状态码和内容类型,来决定请求的成功与失败。虽然AFHTTPRequestOperationManager通常是发送请求最好的方式,但是AFHTTPRequestOperation可以单独使用
1.进行JSON解析
-(void)GETwithAFHTTPRequestOperation{
//网易头条接口
NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://c.m.163.com/nc/ad/headline/0-8.html"]];
AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
requestOperation.responseSerializer = [AFJSONResponseSerializer serializer];
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation * operation, id requestObject) {
NSLog(@"JSON :%@",requestObject);
} failure:^(AFHTTPRequestOperation * operation, NSError * error) {
NSLog(@"error :%@",error);
}];
[[NSOperationQueue mainQueue]addOperation:requestOperation];
}
2.多个上传队列
-(void)BatchofOperations{
NSArray * filesToUpload;
NSMutableArray * mutableOperation = [NSMutableArray array];
for (NSURL * fileURL in filesToUpload) {
NSURLRequest * request = [[AFHTTPRequestSerializer serializer]multipartFormRequestWithMethod:@"POST" URLString:@"" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:fileURL name:@"images[]" error:nil];
}];
AFHTTPRequestOperation * operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
[mutableOperation 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];
}