当以C/S模式连接网络时,client首先要知道server的URL,然后向server发送request。server接受请求并发送response给client,然后不断的向client发送数据(可能分为N次发送完毕)。对照这个过程,我们先进行get方式的异步连接:
- (IBAction)YiBuGet:(id)sender {//get方式 把参数以key/value形式直接拼接到URL后面,参数之间用&分隔 //第一步 设置URL NSURL *url = [NSURL URLWithString:@"http://api.hudong.com/iphonexml.do?type=focus-c"]; //第二步, 创建请求(requset) NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];//缓存策略:基础策略,超时设置:10秒 //第三步 连接服务器 NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self]; }
在connection中,我们设置了NSURLConnectionDataDelegate,因此要实现delegate的一些常用方法:
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error//出现错误 { NSLog(@"%@",[error localizedDescription]); } -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {//收到response NSHTTPURLResponse *res = (NSHTTPURLResponse *)response; NSLog(@"%@",[res allHeaderFields]); self.receivedData = [NSMutableData data]; } -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data//收到数据 { [self.receivedData appendData:data]; } -(void)connectionDidFinishLoading:(NSURLConnection *)connection//下载完毕 { NSString *receivedStr = [[NSString alloc]initWithData:self.receivedData encoding:NSUTF8StringEncoding]; NSLog(@"str = %@",receivedStr); }
异步post方式和get方式大体相同,不过网址中不再需要键值对,而是把它们放在HTTPBody中,还需要设置request方式为post,而NSURLRequest类并没有相关的设置方法,我们需要使用它的子类来设置:
1 - (IBAction)YiBuPost:(id)sender {//异步post 2 //post方式,把URL和参数分开,参数作为postbody发给服务器 3 //第一步 设置URL 4 NSURL *url = [NSURL URLWithString:@"http://api.hudong.com/iphonexml.do"];//此处的地址和get方式时不一样 5 //第二步 创建请求 6 NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10]; 7 [request setHTTPMethod:@"post"]; 8 NSString *str = @"type=focus-c";//把参数信息放在str中,并设置为HTTPBody 9 NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding ]; 10 [request setHTTPBody:data]; 11 NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self]; 12 13 }
相对与异步请求,同步请求不需要设置代理,代码相对简单,但是同步下载会阻塞主线程,造成程序“卡死”,一般在数据量较小,或有特定的需求是才使用:
1 - (IBAction)TongbuGet:(id)sender { 2 //第一步 设置URL 3 NSURL *url = [NSURL URLWithString:@"http://api.hudong.com/iphonexml.do?type=focus-c"]; 4 //第二步, 创建请求(requset) 5 NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];//缓存策略:基础策略,超时设置:10秒 6 //第三步 连接服务器 7 NSURLResponse *response = nil; 8 NSError *error = nil; 9 //不用设置代理,直接就可以得到数据 10 NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 11 12 NSString *str = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding]; 13 NSLog(@"str = %@",str); 14 }
同步post:
1 - (IBAction)TongBUPost:(id)sender { 2 NSURL *url = [NSURL URLWithString:@"http://api.hudong.com/iphonexml.do"]; 3 //第二步 创建请求 4 NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10]; 5 [request setHTTPMethod:@"post"];//设置httpmethod为post 6 NSString *str = @"type=focus-c"; 7 NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding ]; 8 [request setHTTPBody:data];//设置httpbody 9 NSURLResponse *response = nil; 10 NSError *err = nil; 11 //创建连接,得到数据 12 NSData *data1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err]; 13 NSString *str1 = [[NSString alloc]initWithData:data1 encoding:NSUTF8StringEncoding]; 14 NSLog(@"str = %@",str1); 15 }