AFNetworking,是对NSURLConnection、NSURLSession的一层封装服务器
AFHTTPRequestOperationManagerurl
是AFN中最重要的对象之一spa
封装了HTTP请求的常见处理code
GET\POST请求对象
解析服务器的响应数据blog
GET请求io
- (AFHTTPRequestOperation *)GET:(NSString *)URLStringtable
parameters:(id)parametersclass
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];