AFNetworking使用

  • 简介

AFNetworking,是对NSURLConnection、NSURLSession的一层封装

  • 常用类

AFHTTPRequestOperationManager

是AFN中最重要的对象之一

封装了HTTP请求的常见处理

GETPOST请求

解析服务器的响应数据

  • GETPOST请求

GET请求

- (AFHTTPRequestOperation *)GET:(NSString *)URLString

                     parameters:(id)parameters

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

                        failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure

POST请求

- (AFHTTPRequestOperation *)POST:(NSString *)URLString

                      parameters:(id)parameters

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

                         failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure

  • 具体使用步骤

1.创建管理者
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];

2.封装请求参数
NSMutableDictionary *params = [NSMutableDictionary dictionary];
params[@"username"] = @"Test";
params[@"pwd"] = @"123";

3.发送请求

NSString *url = @"http://localhost:8080/Server/login";
[mgr POST:url parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject) {
// 请求成功的时候调用这个block
NSLog(@"请求成功---%@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// 请求失败的时候调用调用这个block
NSLog(@"请求失败");
}];
// GET请求
[mgr GET:url parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject) {
// 请求成功的时候调用这个block
NSLog(@"请求成功---%@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// 请求失败的时候调用调用这个block
NSLog(@"请求失败");
}];

4.对服务器返回数据的解析
1.AFN可以自动对服务器返回的数据进行解析
* 默认将服务器返回的数据当做JSON来解析

2.设置对服务器返回数据的解析方式
1> 当做是JSON来解析(默认做法)
* mgr.responseSerializer = [AFJSONResponseSerializer serializer];
* responseObject的类型是NSDictionary或者NSArray

2> 当做是XML来解析
* mgr.responseSerializer = [AFXMLParserResponseSerializer serializer];
* responseObject的类型是NSXMLParser

3> 直接返回data
* 意思是:告诉AFN不要去解析服务器返回的数据,保持原来的data即可
* mgr.responseSerializer = [AFHTTPResponseSerializer serializer];

原文地址:https://www.cnblogs.com/H7N9/p/4928826.html