iOS NSURLConnection GET和POST

iOS自带的网络请求的类主要为NSURLConnection,后来添加了NSURLConnectionSession。

在NSURLConnection中常用的四个类

  1. NSURL
  2. NSURLRequest
  3. NSURLMutableRequest
  4. NSURLConnection

1.NSURLConnection的GET请求

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

  1. get请求从服务器获取数据,post向服务器发送数据
  2. get将参数添加到url的后面然后请求,post将参数封装起来放到HTTP的请求头重发送
  3. get传送数据量小,post传送数据量大。(一般用于上传数据,上传图片,登录注册等。)
  4. get的安全性非常低,post的安全性较高
  5. 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];
}
当点击的时候就会执行注册操作,然后返回信息,在代理方法中输出该信息。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值