- 本篇内容:
- 1,AFNetworking结构分析:
- 2,AFHTTPSessionManager(get和post请求)
- 3,AFURLSessionManager(文件下载,上传,多文件上传等)
- 4, Request Serialization//请求序列化
- 5, Network Reachability Manager//网络状态监听
- 6,Security Policy
1,AFNetworking结构分析:
NSURLSession
//最主要的两个类
AFHTTPSessionManager
AFURLSessionManager
Serialization
<AFURLRequestSerialization>
AFHTTPRequestSerializer
AFJSONRequestSerializer
AFPropertyListRequestSerializer
<AFURLResponseSerialization>
AFHTTPResponseSerializer
AFJSONResponseSerializer
AFXMLParserResponseSerializer
AFXMLDocumentResponseSerializer (Mac OS X)
AFPropertyListResponseSerializer
AFImageResponseSerializer
AFCompoundResponseSerializer
Additional Functionality
AFSecurityPolicy
AFNetworkReachabilityManager
2,AFHTTPSessionManager
AFHTTPSessionManager是AFURLSessionManager的子类,主要用于便捷的发送http请求:
2.1,发送GET请求:
//创建管理者对象
AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
//配置参数
NSString *str = @"你的地址";
NSMutableDictionary *params = [NSMutableDictionary dictionary];
params[@"username"] = @"123";
params[@"pwd"] = @"123";
//发送请求
[mgr GET:str parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
NSLog(@"%@",downloadProgress);
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"%@",responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"request failed");
}];
2.2,发送POST请求:
//创建管理者对象
AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
//发送请求,str是请求路径(无需转成url),dict是参数字典
NSString *str = @"你的地址";
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[@"username"] = @"123";
dict[@"pwd"] = @"123";
[mgr POST:str parameters:dict progress:^(NSProgress * _Nonnull downloadProgress) {
NSLog(@"%@",downloadProgress);
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"%@",responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"request failed");
}];
注意:
- 默认情况下是默认解析json数据返回oc对象的,也就是说默认是有下面这句的,不用手动写
mgr.responseSerializer = [AFJSONResponseSerializer serializer];
- 如果HTTP返回数据不需要任何转换,则用下面这句表明,返回的是json二进制数据或者XML二进制数据:
mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
- 如果知道是XML文件,自动转换成NSXMLParser并返回,则用下面这句,返回的是xml解析后的NSXMLParser:(注意:由于XML格式不一,所以不能直接获取内部内容,还需要手动解析,但是解析器会返回给你)
mgr.responseSerializer = [AFXMLParserResponseSerializer serializer];
3,AFURLSessionManager
该类是对NSURLSession的封装
3.1,AFURLSessionManager//简介
AFURLSessionManager creates and manages an NSURLSession object based on a specified NSURLSessionConfiguration object, which conforms to <NSURLSessionTaskDelegate>, <NSURLSessionDataDelegate>, <NSURLSessionDownloadDelegate>, and <NSURLSessionDelegate>.
3.2,Creating a Download Task//创建文件下载任务
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
NSLog(@"File downloaded to: %@", filePath);
}];
[downloadTask resume];
3.3,Creating an Upload Task //创建文件单个文件上传
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];
3.4,Creating an Upload Task for a Multi-Part Request, with Progress//创建多值请求上传任务
//请求中可以放置需要的参数,formData是用来放置文件内容的
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]];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
uploadTaskWithStreamedRequest:request
progress:^(NSProgress * _Nonnull uploadProgress) {
// This is not called back on the main queue.
// You are responsible for dispatching to the main queue for UI updates
dispatch_async(dispatch_get_main_queue(), ^{
//Update the progress view
[progressView setProgress:uploadProgress.fractionCompleted];
});
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(@"Error: %@", error);
} else {
NSLog(@"%@ %@", response, responseObject);
}
}];
[uploadTask resume];
3.5,3.4的请求还可以改写成post请求方式进行上传,如下:
//formData放置文件内容
AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
NSMutableDictionary *params = [NSMutableDictionary dictionary];
NSData *data= UIImageJPEGRepresentation(self.imageView.image, 1);
[mgr POST:str parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
[formData appendPartWithFileData:data name:@"file" fileName:@"zhang.jpg" mimeType:@"image/jpeg"];
} progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
}];
3.6,Creating a Data Task//创建数据请求任务
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:@"http://httpbin.org/get"];
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];
4,Request Serialization//请求序列化
- 4.1,Request serializers create requests from URL strings, encoding parameters as either a query string or HTTP body.//主要作用是把字符串和参数序列化成请求
NSString *URLString = @"http://example.com";
NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]};
4.2,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
4.3,URL Form Parameter Encoding
[[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil];
POST http://example.com/
Content-Type: application/x-www-form-urlencoded
foo=bar&baz[]=1&baz[]=2&baz[]=3
4.4,JSON Parameter Encoding
[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil];
POST http://example.com/
Content-Type: application/json
{"foo": "bar", "baz": [1,2,3]}
5,Network Reachability Manager//网络状态监听
AFNetworkReachabilityManager monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces.
- Do not use Reachability to determine if the original request should be sent.
- You should try to send it.
- You can use Reachability to determine when a request should be automatically retried.
- Although it may still fail, a Reachability notification that the connectivity is available is a good time to retry something.
- Network reachability is a useful tool for determining why a request might have failed.
- After a network request has failed, telling the user they're offline is better than giving them a more technical but accurate error, such as "request timed out."
Shared Network Reachability
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
}];
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
6,Security Policy
AFSecurityPolicy evaluates server trust against pinned X.509 certificates and public keys over secure connections.
Adding pinned SSL certificates to your app helps prevent man-in-the-middle attacks and other vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged to route all communication over an HTTPS connection with SSL pinning configured and enabled.
Allowing Invalid SSL Certificates
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.securityPolicy.allowInvalidCertificates = YES; // not recommended for production