IOS开发之AFNetworking开源库的使用

IOS开发之AFNetworking开源库的使用

1.简介

  常见的处理网络请求方式

  (1)NSURLConnection/NSURLSession

  (2)ASIHttpRequest 早期项目中比较常见, 由于作者不更新了

  (3)AFNetworking 推荐使用, 项目中使用

  (4)MKNetworkKit 试试

2.配置和使用

  2.1 配置 

    库文件拖入工程中, 包含头文件 

    #import "AFNetworking.h"

  2.2 使用

     2.2.1.GET请求(html,json,xml

-(void)testGetRequest{
    
    NSString *urlstring = @"http://www.baidu.com";
    urlstring = @"http://m.weather.com.cn/data/101010100.html";
    urlstring = @"http://mp.manzuo.com/china/beijing/home_2.xml";
    
    //定义AFNetworking管理
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    //注意:默认数据是JSON,content-type也是JSON,responseObject是解析字典和数组,不是产生错误Code=-1016
    //解决:设置解析器为HTTP形式,下载回来是NSData
    manager.responseSerializer = [AFCompoundResponseSerializer serializer];
    
    [manager GET:urlstring parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        responseObject重要参数,包含下载数据
//        NSLog(@"o = %@",responseObject);
        
        NSString *str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"str = %@",str);
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error = %@",error);
    }];

}
testGetRequest

     2.2.2.POST请求

-(void)testPostRequest{
    //POST接口:
    //参数1:@"user" : @"quiet"
    //参数2:@"password" : @"123"
    
    NSString *urlString = @"http://quiet.local/testdir/login.php";
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFCompoundResponseSerializer serializer];
    
    //参数1:传入地址
    //参数2:传入URL请求的参数,格式传入字典
    [manager POST:urlString parameters:@{@"user": @"quiet",@"password" : @"123"} success:^(AFHTTPRequestOperation *operation, id responseObject) {
         NSString *str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"str = %@",str);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error = %@",error);
    }];
}
testPostRequest

     2.2.3.上传文件(上传图片)

-(void)testUploadFile{
    
    //POST上传的接口
    NSString *urlString = @"http://quiet.local/uploadtest/pk.php";
    //参数名:image : 参数值是图片
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFCompoundResponseSerializer serializer];
    
    [manager POST:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        NSString *path = [[NSBundle mainBundle]pathForResource:@"daji.jpg" ofType:nil];
        
        [formData appendPartWithFileURL:[NSURL URLWithString:path] name:@"image" fileName:@"666.jpg" mimeType:@"image/jpeg" error:nil];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"str = %@",str);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         NSLog(@"error = %@",error);
    }];
    
    
    [manager POST:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
        //实现:上传的数据附加到请求体中
        //fileName:上传后的文件名
        //mimeType:需要上网搜索mime,把相应的格式复制过来
        NSString *path = [[NSBundle mainBundle]pathForResource:@"daji.jpg" ofType:nil];
    
        [formData appendPartWithFileURL:[NSURL fileURLWithPath:path] name:@"image" fileName:@"666.jpg" mimeType:@"image/jpeg" error:nil];
        
        } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"str = %@",str);

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error = %@",error);
    }];
    
}
testUploadFile

 

     2.2.4.下载文件

-(void)testDownloadFile{
    NSString *urlString = @"http://imgcache.qq.com/club/item/avatar/zip/7/i87/all.zip";
    
    //创建会话管理对象(通过默认配置)
    AFURLSessionManager *manager = [[AFURLSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]] progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        
        //返回文件保存的位置
        NSString *path = [NSString stringWithFormat:@"%@/Documents/all.zip",NSHomeDirectory()];
        NSLog(@"%@",NSHomeDirectory());
        return [NSURL fileURLWithPath:path];
        
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        NSLog(@"下载完成");
    }];
    
    //启动任务
    [task resume];
    
}
testDownloadFile

     2.2.5.监控网络状态

-(void)testMonitorNetworkStatus{
    
    AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc]initWithBaseURL:[NSURL URLWithString:@"www.baidu.com"]];
    [manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        NSDictionary *dict = @{
            @(AFNetworkReachabilityStatusUnknown): @"未知",
            @(AFNetworkReachabilityStatusNotReachable): @"不可达",
            @(AFNetworkReachabilityStatusReachableViaWWAN): @"GPRS",
            @(AFNetworkReachabilityStatusReachableViaWiFi): @"Wifi",
            };
        NSLog(@"状态为 %@",dict[@(status)]);
        
    }];
    //开启状态监视
    [manager.reachabilityManager startMonitoring];

}
testMonitorNetworkStatus

     2.2.6.图片异步功能(替代SDWebImage

          导入头文件

          #import "UIKit+AFNetworking.h"

          - (void)setImageWithURL:(NSURL *)url;

     2.2.7.有一些特殊的请求头

         BAIDU_WISE_UID=wapp_1428385381699_466;

         AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];  

         [manager.requestSerializer setValue:@"wapp_1428385381699_466" forHTTPHeaderField:@"BAIDU_WISE_UID"]; 

posted @ 2015-04-19 12:20  BadMao  阅读(495)  评论(0编辑  收藏  举报