Cowboy Tech

AFNetworking简介

HTTP请求

NSString *urlStr = @"http://api.openweathermap.org/data/2.5/forecast/city?id=524901&APPID=bf791ba9eeca14dd22823b4c21ce7e2d";

AFHTTPRequestOperationManager *manager            = [AFHTTPRequestOperationManager manager];

// 设置回复内容信息
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes
                                                     setByAddingObject:@"text/html"];

[manager GET:urlStr
  parameters:nil

     success:^(AFHTTPRequestOperation *operation, id responseObject) {

         //请求正文数据
         //NSLog(@"%@",responseObject);

         //请求头部信息(我们执行网络请求的时候给服务器发送的信息)
         //NSLog(@"%@",operation.request.allHTTPHeaderFields);

         //服务器返回的包的头部信息
         NSLog(@"%@",operation.response);
     }
     failure:^(AFHTTPRequestOperation *operation, NSError *error) {

         NSLog(@"%@",error);

     }];

请求方法

(GET、POST等)

Hypertext Transfer Protocol

// 执行POST请求,需要将参数写在parameter处,而不能如同get方法一样直接写在地址栏

[manager POST:@"http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo"
   parameters:@{@"mobileCode" : @"15910514636",
                @"userID"     : @""}
      success:^(AFHTTPRequestOperation *operation, id responseObject) {
          NSLog(@"%@", responseObject);

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

请求头

(HttpHeaderFields)

List of HTTP header fields

//请求头部信息(我们执行网络请求的时候给服务器发送的信息)
NSLog(@"%@",operation.request.allHTTPHeaderFields);

请求正文 (数据)

问号后的字符串,使用get方法是可以在地址栏中看见的

NSString *urlStr = @"http://api.openweathermap.org/data/2.5/forecast/city?id=524901&APPID=bf791ba9eeca14dd22823b4c21ce7e2d";            

序列化

采用不同的序列化格式,得到不同的response结果

AFHTTPRequestOperationManager *manager            = [AFHTTPRequestOperationManager manager];

// 请求的序列化
manager.requestSerializer = [AFHTTPRequestSerializer serializer];

// 回复序列化

//responseObject就变成二进制文件
manager.responseSerializer[AFHTTPResponseSerializer serializer];

//responseObject就变成JSON格式
manager.responseSerializer = [AFJSONResponseSerializer serializer];

//responseObject成为xml格式
manager.responseSerializer = [AFXMLParserResponseSerializer serializer];

上传文件

// 获取数据
UIImage *image  = [UIImage imageNamed:@"demo"];
NSData *dataObj = UIImageJPEGRepresentation(image, 1.0);

// 参数
NSDictionary *paras = @{@"ContactName"        : @"Lilis",
                        @"ContactPhoneNumber" : @"15910514635",
                        @"LoseDetail"         : @"...",
                        @"address"            : @"",
                        @"gender"             : @"2",
                        @"verify"             : @"012460"};


[Networking UploadDataWithUrlString:BASE_URL // 请更换网址
                         parameters:paras
                    timeoutInterval:nil
                        requestType:HTTPRequestType
                       responseType:JSONResponseType
          constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
              // 构造数据的地方
              [formData appendPartWithFileData:dataObj name:@"upload" fileName:@"image1.jpg" mimeType:@""];
              [formData appendPartWithFileData:dataObj name:@"upload" fileName:@"image2.jpg" mimeType:@""];
          }
                            success:^(AFHTTPRequestOperation *operation, id responseObject) {

                                // 请求头
                                NSLog(@"%@", operation.request.allHTTPHeaderFields);

                                // 服务器回复的头
                                NSLog(@"%@", operation.response);

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


                            }];

断点下载

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://c.hiphotos.baidu.com/image/pic/item/f3d3572c11dfa9ec78e256df60d0f703908fc12e.jpg"]];
AFDownloadRequestOperation *operation = [[AFDownloadRequestOperation alloc] initWithRequest:request
                                                                             fileIdentifier:@"fuck.jpg"
                                                                                 targetPath:[NSHomeDirectory() stringByAppendingPathComponent:@"/Library/Caches/fuck.jpg"]
                                                                               shouldResume:YES];
operation.shouldOverwrite = YES;


// 开始下载
[operation start];

// 2s后暂停
[GCDQueue executeInMainQueue:^{
    NSLog(@"暂停");
    [operation pause];
} afterDelaySecs:2.f];

// 4s后继续恢复
[GCDQueue executeInMainQueue:^{
    NSLog(@"开始");
    [operation resume];
} afterDelaySecs:4.f];

// 查看下载进度
[operation setProgressiveDownloadProgressBlock:^(AFDownloadRequestOperation *operation, NSInteger bytesRead, long long totalBytesRead, long long totalBytesExpected, long long totalBytesReadForFile, long long totalBytesExpectedToReadForFile) {

    CGFloat percent = (float)totalBytesReadForFile / (float)totalBytesExpectedToReadForFile;
    NSLog(@"百分比:%.3f%% %ld  %lld  %lld  %lld", percent * 100, (long)bytesRead, totalBytesRead, totalBytesReadForFile, totalBytesExpectedToReadForFile);
}];

// 结束block
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

    NSLog(@"下载成功 %@", responseObject);

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    NSLog(@"下载失败 %@", error);

}];

监听网络

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

// 开启网络指示器
[[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];

NSURL *url = [NSURL URLWithString:@"http://baidu.com"];

AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:url];
NSOperationQueue *operationQueue       = manager.operationQueue;

[manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {

    switch (status) {
        case AFNetworkReachabilityStatusReachableViaWWAN:
        case AFNetworkReachabilityStatusReachableViaWiFi:

            [operationQueue setSuspended:NO];

            NSLog(@"有网络");

            break;

        case AFNetworkReachabilityStatusNotReachable:
        default:

            [operationQueue setSuspended:YES];

            NSLog(@"无网络");

            break;
    }

}];

// 开始监听
[manager.reachabilityManager startMonitoring];

return YES;
}

下载图片(Category)

#import "ViewController.h"
#import "AFNetworking.h"
#import "UIKit+AFNetworking.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:imageView];

// 加载图片
[imageView setImageWithURL:[NSURL URLWithString:@"http://c.hiphotos.baidu.com/image/pic/item/f3d3572c11dfa9ec78e256df60d0f703908fc12e.jpg"]
          placeholderImage:nil];
}