在iOS中,常见的发送HTTP请求的方案有
苹果原生(自带)
- NSURLConnection:用法简单,最古老最经典的一种方案
- NSURLSession:功能比NSURLConnection更加强大,推荐使用这种技术(2013年推出)
- CFNetwork:NSURL的底层,纯C语言
第三方框架
- ASIHttpRequest:外号:“HTTP终结者”,功能及其强大,早已不维护
- AFNETworking:简单易用,提供了基本够用的常用功能,维护和使用者居多
- MKNetworkKit:简单易用,来自印度,维护使用者少
建议
为了提高开发效率,企业开发用的基本是第三方框架
一.使用NSURLConnection
NSURLConnection常见的发送请求方法有以下几种
//同步请求 + (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error;
//异步请求:根据对服务器返回数据的处理方式的不同,又可以分为2种 //block回调 + (void)sendAsynchronousRequest:(NSURLRequest*) request queue:(NSOperationQueue*) queue completionHandler:(void (^)(NSURLResponse* response, NSData* data, NSError* connectionError)) handler; //代理 - (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate; + (NSURLConnection*)connectionWithRequest:(NSURLRequest *)request delegate:(id)delegate; - (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate startImmediately:(BOOL)startImmediately;
代理相关的方法
#pragma mark -NSURLConnectionDelegate - begin /** 请求失败(比如请求超时) */ - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { } /** 接收到服务器的响应 */ - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { NSLog(@"didReceiverResponse"); //初始化 self.responseData = [NSMutableData data]; } /** 接收到服务器的数据(如果数据量比较大,这个方法会调用多次) */ - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { NSLog(@"didReceiveData - %zd",data.length); //拼接 [self.responseData appendData:data]; } /** 服务器的数据成功,接收完毕 */ - (void)connectionDidFinishLoading:(NSURLConnection *)connection { NSLog(@"connectionDidFinishLoading"); //显示数据 NSString *str = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding]; NSLog(@"%@",str); }
二.使用NSURLSession
使用NSURLSession对象创建Task,然后执行Task
1.使用NSURLSessionDataTask
post请求
- (void)post { //获取NSURLSession对象 NSURLSession *session = [NSURLSession sharedSession]; //创建请求 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/images/minion_01.png"]]; request.HTTPMethod = @"POST"; request.HTTPBody = [@"username=520it&pwd=520it" dataUsingEncoding:NSUTF8StringEncoding]; //创建任务 NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { NSLog(@"%@",[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]); }]; //启动任务 [task resume]; }
get请求
- (void)get { NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionDataTask *task = [session dataTaskWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/login?username=123&pwd=123"] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { NSLog(@"%@",[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]); }]; //启动 [task resume]; }
代理方法
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]]; NSURLSessionDataTask *task = [session dataTaskWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/login?username=123&pwd=123"]]; //启动 [task resume]; } #pragma mark -<NSURLSessionDataDelegate> /** * 1.接收到服务器的响应 */ - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler { NSLog(@"----%s----",__func__); //允许处理服务器的响应 completionHandler(NSURLSessionResponseAllow); } /** * 2.接收到服务器的数据(可能会被调用多次) */ - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data { NSLog(@"----%s----",__func__); } /** * 3.请求成功或者失败(如果失败,error有值) */ - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { NSLog(@"----%s----",__func__); }
二.使用AFNetworking框架
网址:https://github.com/AFNetworking/AFNetworking
AFHTTPRequestOperationManager内部包装了NSURLConnection
- (void)get { AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager]; NSDictionary *params = @{ @"username" : @"520it", @"pwd" : @"520it" }; [mgr GET:@"http://120.25.226.186:32812/login" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"请求成功----%@",[responseObject class]); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"请求失败----%@",error); }]; }
AFHTTPSessionManager内部包装了NSURLSession
- (void)get2 { //AFHTTPSessionManager内部包装了NSURLSession AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager]; NSDictionary *params = @{ @"username" : @"520it", @"pwd" : @"520it" }; [mgr GET:@"http://120.25.226.186:32812/login" parameters:params success:^(NSURLSessionDataTask *task, id responseObject) { NSLog(@"请求成功----%@",[responseObject class]); } failure:^(NSURLSessionDataTask *task, NSError *error) { NSLog(@"请求失败----%@",error); }]; }
AFN这个框架默认使用了JSON解析器,如果服务器返回的是XML格式的
你需要将框架中的解析器换成XML解析器
AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager]; //responseSerializer 用来解析服务器返回的数据 //告诉AFN 以XML形式解析服务器返回的数据 mgr.responseSerializer = [AFXMLParserResponseSerializer serializer];