iOS自带的网络请求的类主要为NSURLConnection,后来添加了NSURLConnectionSession。
在NSURLConnection中常用的四个类
1.NSURLConnection的GET请求
涉及到GET和POST的请求,那么就必须说明下GET和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]; }); }
self.window.rootViewController = [[NetWorkViewController alloc]init];于是运行后就可以下载出图片然后设置了。
2.POST请求。
NSURLConnection的post请求用的是NSMutableURLRequest对象。
首先需要私有化成员变量
{ NSMutableData * _data; }接下来初始化NSURLConnection。记得要用NSMutableRequest。
该请求对象必须设置几个属性:
1.请求方法类型 post/get
[request setHTTPMethod:@"post"];
[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];
[NSURLConnection connectionWithRequest:request delegate:self];
-(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]; }当点击的时候就会执行注册操作,然后返回信息,在代理方法中输出该信息。