您的位置:首页 > 移动开发 > IOS开发

iOS NSURLConnection GET和POST

2015-11-30 20:50 441 查看
iOS自带的网络请求的类主要为NSURLConnection,后来添加了NSURLConnectionSession。

在NSURLConnection中常用的四个类

NSURL
NSURLRequest
NSURLMutableRequest
NSURLConnection

1.NSURLConnection的GET请求

涉及到GET和POST的请求,那么就必须说明下GET和POST的区别。

get请求从服务器获取数据,post向服务器发送数据
get将参数添加到url的后面然后请求,post将参数封装起来放到HTTP的请求头重发送
get传送数据量小,post传送数据量大。(一般用于上传数据,上传图片,登录注册等。)
get的安全性非常低,post的安全性较高
DQL类操作常用get,其他DML的操作用post。

首先我们私有化两个变量。宏定义path

#define path @"http://p2.qhimg.com/t01b6e2b437cad4091d.jpg"
{
NSMutableData * _data;
NSURLConnection * _connection;
}然后初始化链接对象和添加imageview

-(void)loadData
{
_data = [[NSMutableData alloc]init];
NSURLRequest * request = [[NSURLRequest alloc]initWithURL:[NSURL URLWithString:path]];
_connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
}
-(void)addView
{
UIImageView * imgView = [[UIImageView alloc]init];
imgView.frame = CGRectMake(100, 100, 200, 150);
[self.view addSubview:imgView];
_imgView = imgView;
}
然后遵守代理,NSURLConnectionDataDelegate,实现内部协议方法
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(@"%@",@"收到数据了");
[_data appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"%@",@"下载完毕");
//GCD主线程刷新UI
dispatch_async(dispatch_get_main_queue(), ^{
_imgView.image = [UIImage imageWithData:_data];

});
}

AppDelegate中指定当前的viewcontroller为根视图控制器。
self.window.rootViewController = [[NetWorkViewController alloc]init];于是运行后就可以下载出图片然后设置了。
2.POST请求。
NSURLConnection的post请求用的是NSMutableURLRequest对象。
首先需要私有化成员变量
{
NSMutableData * _data;
}接下来初始化NSURLConnection。记得要用NSMutableRequest。
该请求对象必须设置几个属性:
1.请求方法类型 post/get 
[request setHTTPMethod:@"post"];
2.设置Content-Type

[request setValue:@"Content-Type"
forHTTPHeaderField:@"application/x-www-form-urlencoded"];
这个地方需要注意
3.设置Content-Length
NSString * bodyStr = [NSString stringWithFormat:@"username=%@&password=%@&email=%@",name,pass,email];
NSData * bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
[request setValue:[NSString stringWithFormat:@"%ld",bodyData.length] forHTTPHeaderField:@"Content-Length"];
4.设置请求体

[request setHTTPBody:bodyData];

5.开始请求。
[NSURLConnection connectionWithRequest:request delegate:self];


然后需要遵守NSURLConnectionDataDelegate的协议,实现协议方法
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
//如果data==nil 初始化 否则 清空
if (_data == nil) {
_data = [NSMutableData data];
}else {
_data.length = 0;
}
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(@"%@",@"接收到数据 加入data中");
[_data appendData:data];
}
//完成请求
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"%@",@"完成请求,返回数据");
// NSError * error = [NSError errorWithDomain:<#(NSString *)#> code:<#(NSInteger)#> userInfo:<#(NSDictionary *)#>];
NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:_data options:NSJSONReadingAllowFragments error:nil];
NSString * str = dict[@"message"];
NSLog(@"%@",str);
}为按钮设置一个点击事件,在里面设置以上提到的项目:
- (IBAction)registerBtnClicked:(id)sender {
//post请求
//将请求数据字符串->nsurl
NSURL *url = [NSURL URLWithString:PATH];

//get请求封装的请求对象shiNSURLRequest
//post请求封装的请求对象是NSMuTableURLRequest
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];

//设置请求方式
//get不需要
[request setHTTPMethod:@"post"];
//设置请求样式
//请求体的格式是 参数名=参数值&参数名=参数值
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
NSString * bodyStr = [NSString stringWithFormat:@"username=%@&password=%@&email=%@",_nameTextField.text,
_pwdTextField.text,_emailTextField.text];
//设置请求体的长度
//注意 设置请求体的长度 就是设置请求体转化为NSData类型的长度。
NSData * bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
[request setValue:[NSString stringWithFormat:@"%ld",bodyData.length] forHTTPHeaderField:@"Content-Length"];

//设置请求体
[request setHTTPBody:bodyData];

//开始请求
[NSURLConnection connectionWithRequest:request delegate:self];
}
当点击的时候就会执行注册操作,然后返回信息,在代理方法中输出该信息。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: