IOS网络学习-6、NSURLConnection基本使用
来源:互联网 发布:distinct sql 用法 编辑:程序博客网 时间:2024/05/29 04:40
以下内容转载自http://www.cnblogs.com/wendingding/p/3813572.html
一、NSURLConnection的常用类
(1)NSURL:请求地址
(2)NSURLRequest:封装一个请求,保存发给服务器的全部数据,包括一个NSURL对象,请求方法、请求头、请求体....
(3)NSMutableURLRequest:NSURLRequest的子类
(4)NSURLConnection:负责发送请求,建立客户端和服务器的连接。发送NSURLRequest的数据给服务器,并收集来自服务器的响应数据
使用NSURLConnection发送请求的步骤很简单
(1)创建一个NSURL对象,设置请求路径(设置请求路径)
(2)传入NSURL创建一个NSURLRequest对象,设置请求头和请求体(创建请求对象)
(3)使用NSURLConnection发送NSURLRequest(发送请求)
2.代码示例
(1)发送请求的三个步骤:
<span style="background-color: rgb(255, 255, 255);">- (IBAction)Login:(id)sender { if (userName.text.length == 0) { UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Message" message:@"请输入用户名" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; [alert show]; return ; } if (passWd.text.length == 0) { UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Message" message:@"请输入密码" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; [alert show]; return ; } NSString *urlStr =[[NSString alloc] initWithFormat:@"http://192.168.175.130/login?user=%@&pwd=%@",userName.text,passWd.text]; NSURL *url = [[NSURL alloc]initWithString:urlStr]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init]; [request setURL:url]; request.timeoutInterval = 10.0; NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; NSString *message; if (data.length) { message = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; } else{ message = @"用户密码不匹配"; } UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Message" message:message delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; [alert show];}</span>
<span style="background-color: rgb(255, 255, 255);">- (IBAction)Login:(id)sender { if (userName.text.length == 0) { UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Message" message:@"请输入用户名" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; [alert show]; return ; } if (passWd.text.length == 0) { UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Message" message:@"请输入密码" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; [alert show]; return ; } #if 0 NSString *urlStr =[[NSString alloc] initWithFormat:@"http://192.168.175.130/login?user=%@&pwd=%@",userName.text,passWd.text]; NSURL *url = [[NSURL alloc]initWithString:urlStr]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init]; [request setURL:url]; request.timeoutInterval = 10.0; NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; NSString *message; if (data.length) { message = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; } else{ message = @"用户密码不匹配"; } UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Message" message:message delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; [alert show];#endif #if 1 NSString *urlStr =[[NSString alloc] initWithFormat:@"http://192.168.175.130/login?user=%@&pwd=%@",userName.text,passWd.text]; NSURL *url = [[NSURL alloc]initWithString:urlStr]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; //获取主队列 NSOperationQueue *queue = [NSOperationQueue mainQueue]; [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { NSLog(@"--block回调数据--%@---%ld", [NSThread currentThread],data.length); if (data) { NSString *dict = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"------%@--------",dict); } else{ NSLog(@"当前网络忙"); } }];#endif}</span>
要监听服务器返回的data,所以使用<NSURLConnectionDataDelegate>协议
常见大代理方法如下:
<span style="background-color: rgb(255, 255, 255);">#pragma mark- NSURLConnectionDataDelegate代理方法//当接收到服务器的响应(连通了服务器)时会调用-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response//当接收到服务器的数据时会调用(可能会被调用多次,每次只传递部分数据)-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data//当服务器的数据加载完毕时就会调用-(void)connectionDidFinishLoading:(NSURLConnection *)connection//请求错误(失败)的时候调用(请求超时\断网\没有网\,一般指客户端错误)-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error</span>使用异步方法发送get请求的代码示例:
<span style="background-color: rgb(255, 255, 255);">//// YYViewController.m// 01-NSURLConnection的使用(GET)//// Created by apple on 14-6-28.// Copyright (c) 2014年 itcase. All rights reserved.//#import "YYViewController.h"#import "MBProgressHUD+MJ.h"@interface YYViewController ()<NSURLConnectionDataDelegate>@property (weak, nonatomic) IBOutlet UITextField *username;@property (weak, nonatomic) IBOutlet UITextField *pwd;@property(nonatomic,strong)NSMutableData *responseData;- (IBAction)login;@end@implementation YYViewController- (IBAction)login {// 1.提前的表单验证 if (self.username.text.length==0) { [MBProgressHUD showError:@"请输入用户名"]; return; } if (self.pwd.text.length==0) { [MBProgressHUD showError:@"请输入密码"]; return; }// 2.发送请求给服务器(带上账号和密码) //添加一个遮罩,禁止用户操作 [MBProgressHUD showMessage:@"正在努力加载中...."];//// 2.1设置请求路径 NSString *urlStr=[NSString stringWithFormat:@"http://192.168.1.53:8080/MJServer/login?username=%@&pwd=%@",self.username.text,self.pwd.text]; NSURL *url=[NSURL URLWithString:urlStr]; // 2.2创建请求对象// NSURLRequest *request=[NSURLRequest requestWithURL:url];//默认就是GET请求 //设置请求超时 NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url]; request.timeoutInterval=5.0; // 2.3.发送请求 //使用代理发送异步请求(通常应用于文件下载) NSURLConnection *conn=[NSURLConnection connectionWithRequest:request delegate:self]; [conn start]; NSLog(@"已经发出请求---");}#pragma mark- NSURLConnectionDataDelegate代理方法/* *当接收到服务器的响应(连通了服务器)时会调用 */-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{ NSLog(@"接收到服务器的响应"); //初始化数据 self.responseData=[NSMutableData data];}/**当接收到服务器的数据时会调用(可能会被调用多次,每次只传递部分数据)*/-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ NSLog(@"接收到服务器的数据"); //拼接数据 [self.responseData appendData:data]; NSLog(@"%d---%@--",self.responseData.length,[NSThread currentThread]);}/* *当服务器的数据加载完毕时就会调用 */-(void)connectionDidFinishLoading:(NSURLConnection *)connection{ NSLog(@"服务器的数据加载完毕"); //隐藏HUD [MBProgressHUD hideHUD]; //处理服务器返回的所有数据 NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:nil]; //判断后,在界面提示登录信息 NSString *error=dict[@"error"]; if (error) { [MBProgressHUD showError:error]; }else { NSString *success=dict[@"success"]; [MBProgressHUD showSuccess:success]; } NSLog(@"%d---%@--",self.responseData.length,[NSThread currentThread]);}/* *请求错误(失败)的时候调用(请求超时\断网\没有网\,一般指客户端错误) */-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{// NSLog(@"请求错误"); //隐藏HUD [MBProgressHUD hideHUD]; [MBProgressHUD showError:@"网络繁忙,请稍后重试!"];}@end</span>
打印查看:
补充:
(1)数据的处理
在didReceiveData:方法中,拼接接收到的所有数据,等所有数据都拿到后,在connectionDidFinishLoading:方法中进行处理
(2)网络延迟
在做网络开发的时候,一定要考虑到网络延迟情况的处理,可以在服务器的代码设置一个断点模拟。
在服务器代码的登录方法中设置断点
设置请求的最大延迟
模拟器情况:
打印查看:
三、NSMutableURLRequest
NSMutableURLRequest是NSURLRequest的子类,常用方法有
设置请求超时等待时间(超过这个时间就算超时,请求失败)- (void)setTimeoutInterval:(NSTimeInterval)seconds;
设置请求方法(比如GET和POST)- (void)setHTTPMethod:(NSString *)method;
设置请求体- (void)setHTTPBody:(NSData *)data;
设置请求头- (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field;
- IOS网络学习-6、NSURLConnection基本使用
- IOS学习 NSURLConnection基本使用
- iOS 网络篇6—NSURLConnection基本使用
- iOS开发网络篇—NSURLConnection基本使用
- iOS开发网络篇—NSURLConnection基本使用
- iOS开发网络篇—NSURLConnection基本使用
- iOS开发网络篇—NSURLConnection基本使用
- iOS开发网络—06NSURLConnection基本使用
- iOS开发网络篇—NSURLConnection基本使用
- iOS开发网络篇—NSURLConnection基本使用
- iOS开发网络篇—NSURLConnection基本使用
- iOS开发网络篇—NSURLConnection基本使用
- iOS开发网络篇—NSURLConnection基本使用
- iOS开发网络篇—NSURLConnection基本使用
- iOS开发网络篇—NSURLConnection基本使用
- iOS开发网络篇—NSURLConnection基本使用
- iOS开发网络篇—NSURLConnection基本使用
- iOS开发网络篇—NSURLConnection基本使用
- 计算机书记推荐
- Maven针对不同的环境使用Profile完成打包部署
- Jquery(九)jquery工具函数
- java自定义注解
- 关于嵌套子查询的理解
- IOS网络学习-6、NSURLConnection基本使用
- Jquery(十)jqueryUI常用功能实战
- POJ 题目1458 Common Subsequence(最长公共子序列长度纯模板)
- 判断数据库某字段是否存在
- 十天内掌握线性代数:惊人的超速学习实验
- [iOS] UIButton 不响应或延迟响应 UIControlEventTouchDown 事件的解决办法
- 长吐一口气~树形DP汇总(POJ 2486 3659 2342 1947 1463 hdu 2412 )
- eclipse 反编译插件 jdeclipse【常用简便易用】
- Jquery(十一)实战表单验证与自动完成提示插件