我在之前一篇博客中实现了使用NSURLConnection或者NSURLSession来请求网络数据,用的都是苹果自带的方法。请参考《iOS开发——网络请求案例汇总》。现在我们使用最流行的AFNetworking库来进行网络请求。代码我已经上传至https://github.com/chenyufeng1991/iOS-NetworkRequest 。
【1.AFNetworking请求SOAP】
SOAP一般需要我们发送XML数据,返回的一般也是XML数据。我这里用的也是http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx 。这个网站的手机号码归属地查询。不过经过我测试,时间延迟会比较长。。实现方式如下:
#import "AFNsoapViewController.h"
#import <AFNetworking.h>
@interface AFNsoapViewController ()
@end
@implementation AFNsoapViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 创建SOAP消息,内容格式就是网站上提示的请求报文的主体实体部分 这里使用了SOAP1.2;
NSString *soapMsg = [NSString stringWithFormat:
@"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
"<soap12:Envelope "
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" "
"xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">"
"<soap12:Body>"
"<getMobileCodeInfo xmlns=\"http://WebXml.com.cn/\">"
"<mobileCode>%@</mobileCode>"
"<userID>%@</userID>"
"</getMobileCodeInfo>"
"</soap12:Body>"
"</soap12:Envelope>", @"18888888888", @""];
NSURL *url = [NSURL URLWithString: @"http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx"];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:@"%lu", (unsigned long)[soapMsg length]];
[req addValue:@"application/soap+xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[req addValue:msgLength forHTTPHeaderField:@"Content-Length"];
[req setHTTPMethod:@"POST"];
[req setHTTPBody: [soapMsg dataUsingEncoding:NSUTF8StringEncoding]];
AFHTTPRequestOperation *operate = [[AFHTTPRequestOperation alloc] initWithRequest:req];
operate.responseSerializer = [AFHTTPResponseSerializer serializer];
[operate setCompletionBlockWithSuccess:^(AFHTTPRequestOperation * _Nonnull operation, id _Nonnull responseObject) {
NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"成功:%@",result);
} failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
NSLog(@"成功:%@",error);
}];
[operate start];
}
@end
打印结果如下:
。
【2.AFHTTPRequestOperationManager请求Http】
这里直接用一个链接请求服务器数据,可以使用GET或者POST请求。参数直接写入到链接中。实现方式如下:
#import "AFNHttp1ViewController.h"
#import <AFNetworking.h>
@interface AFNHttp1ViewController ()
@end
@implementation AFNHttp1ViewController
- (void)viewDidLoad {
[super viewDidLoad];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//这里改成POST,就可以进行POST请求;
//把要传递的参数直接放到URL中;而不是放到字典中;
[manager GET:@"http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo?mobileCode=18888888888&userId="
parameters:nil
success:^(AFHTTPRequestOperation *operation,id responseObject){
NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"成功: %@", string);
}
failure:^(AFHTTPRequestOperation *operation,NSError *error){
NSLog(@"失败: %@", error);
}];
}
@end
。
【3.AFHTTPRequestOperationManager请求Http改进版】
在2的例子中,我们把参数放到了请求的链接中,并不是特别的方便,这里我们使用字典来存放需要发送的数据。实现如下:
#import "AFNHttp2ViewController.h"
#import <AFNetworking.h>
@interface AFNHttp2ViewController ()
@end
@implementation AFNHttp2ViewController
- (void)viewDidLoad {
[super viewDidLoad];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSDictionary *dic = @{@"mobileCode":@"18888888888",
@"userID":@""};
//这里改成POST,就可以进行POST请求;
[manager GET:@"http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo"
parameters:dic
success:^(AFHTTPRequestOperation *operation,id responseObject){
NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"成功: %@", string);
}
failure:^(AFHTTPRequestOperation *operation,NSError *error){
NSLog(@"失败: %@", error);
}];
}
@end
打印结果与2一样。
【4.AFHTTPRequestOperation请求Http】
在3的例子中,我们通过发送参数列表和链接地址来进行网络请求。现在我们设置一个Request,把这些数据都放到request参数中,然后通过只发送一个request来实现。
#import "AFNHttp3ViewController.h"
#import <AFNetworking.h>
@interface AFNHttp3ViewController ()
@end
@implementation AFNHttp3ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *url = [NSURL URLWithString: @"http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo?mobileCode=18888888888&userId="];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
[req setHTTPMethod:@"GET"];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:req];
operation.responseSerializer = [AFHTTPResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation * _Nonnull operation, id _Nonnull responseObject) {
NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"成功:%@",result);
} failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
NSLog(@"失败:%@",error);
}];
[operation start];
}
@end
【5.AFnetworking发送XML进行Http请求】
这种方式平时不多见,这里把“***”作为字典中的键,把XML作为字典中的值进行发送。并且还要进行安全性的设置。实现代码如下:
#import "AFNXMLHttpViewController.h"
#import <AFNetworking.h>
@interface AFNXMLHttpViewController ()
@end
@implementation AFNXMLHttpViewController
- (void)viewDidLoad {
[super viewDidLoad];
/*
这里需要进行如下的安全性设置;
使用AFNetworking发送XML,如果不进行如下的设置,将会报错:
Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
*/
AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
[securityPolicy setAllowInvalidCertificates:YES];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager setSecurityPolicy:securityPolicy];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSString *str = @"这里存放需要发送的XML";
NSDictionary *parameters = @{@"test" : str};//test是这个XML对应的名字
[manager POST:@"需要发送的链接"
parameters:parameters
success:^(AFHTTPRequestOperation *operation,id responseObject){
NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"成功: %@", string);
}
failure:^(AFHTTPRequestOperation *operation,NSError *error){
NSLog(@"失败: %@", error);
}];
}
@end
总结,使用AFNetworking进行网络请求还是比较简单的,我会继续深入的研究AFNetworking,有任何成果都会分享给大家。
最近开源的iOS应用,高仿印象笔记 https://github.com/chenyufeng1991/iOS-Oncenote 。欢迎大家点赞并关注项目进度。也可以安装到手机上试玩哦。
github主页:https://github.com/chenyufeng1991 。欢迎大家访问!