网络请求三部
创建一个请求(添加接口,对接口进行解码,)
设定请求方式(将接口转为NSURL,设置请求[请求地址, 缓存策略, 超时时间],设置请求方式)
连接服务器([同步连接,异步连接]代理连接,block连接)
#import "MainViewController.h" @interface MainViewController () @property (retain, nonatomic) IBOutlet UIImageView *ImageWiew; //get请求方法 - (IBAction)getConnection:(id)sender; //post请求方法 - (IBAction)postConnection:(id)sender; //协议方式实现异步连接服务器 - (IBAction)buttonDelegate:(id)sender; //block异步连接服务器 - (IBAction)buttonBlock:(id)sender; //一个可变的数据属性,用于拼接每次从服务器请求的小数据块 @property (nonatomic , retain)NSMutableData *receiveData; @end @implementation MainViewController - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization // //初始化方法 // self.receiveData = [NSMutableData data]; } return self; } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } /* #pragma mark - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ - (void)dealloc { [_ImageWiew release]; [super dealloc]; } - (IBAction)getConnection:(id)sender { //实现网络请求_get请求方式 //注意错误:地址不能有错,网络不能断 NSString *str = @"http://cdn.gq.com.tw.s3-ap-northeast-1.amazonaws.com/userfiles/p_w_picpaths_A1/6954/2011100658141857.jpg"; //要请求的图片地址 //网络请求三步 //1.创建一个请求,设定请求方式(GET/POST) NSURL *url = [NSURL URLWithString:str]; //参数1:请求的地址信息(需要转成URL类型) //参数2;请求的缓存策略(缓存策略,服务器指定的) //参数3:设置超时的时间 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60]; //设置请求方式 request.HTTPMethod = @"GET"; //2.连接服务器,发送请求 //连接服务器两种不同的方式: 一,同步连接 二,异步连接 //同步连接服务器 //参数1:要发送的网络请求 //参数2:服务器对这次请求的响应信息 NSURLResponse *response = nil; NSError *error = nil; //这个方法会卡住整个应用程序,直到完整的数据被请求下来之后才继续执行 NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; //把请求下来的数据(data)转换成图片 UIImage *p_w_picpath = [UIImage p_w_picpathWithData:data]; self.ImageWiew.p_w_picpath = p_w_picpath; NSLog(@"服务器响应信息:%@", response); NSLog(@"错误信息:%@", error); } - (IBAction)postConnection:(id)sender { //创建一个post请求 //1.创建一个请求,设定pos NSString *str = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"; NSURL *url = [NSURL URLWithString:str]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60]; //设置请求方式 request.HTTPMethod = @"POST"; //post请求,需要带一个数据; NSString *strBody = @"date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213"; //把一段字符串转换为NSData类型,方便发送; request.HTTPBody = [strBody dataUsingEncoding:NSUTF8StringEncoding]; //2.连接服务器 NSURLResponse *response = nil; NSError *error = nil; NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; //转为字符串检测是什么类型的数据 NSString *resultStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"结果:%@",resultStr); NSLog(@"服务器响应信息%@", response); } - (IBAction)buttonDelegate:(id)sender { //基于协议的异步请求 //创建一个请求 NSString *string = @"http://api.douban.com/v2/movie/nowplaying?app_name=doubanmovie&client=e:iPhone4,1|y:iPhoneOS_6.1|s:mobile|f:doubanmovie_2|v:3.3.1|m:PP_market|udid:aa1b815b8a4d1e961347304e74b9f9593d95e1c5&alt=json&version=2&start=0&city=北京&apikey=0df993c66c0c636e29ecbb5344252a4a"; //带有特殊字符的汉子(汉字,|,..)需要提前转码 NSString *newStr = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url = [NSURL URLWithString:newStr]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60]; request.HTTPMethod = @"get"; //2.连接服务器 //创建一个网络连接对象 //设置网络连接的代理(这个代理有三个必须要实现的方法)(记得加代理<NSURLConnectionDataDelegate>) NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; } - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { //接收到服务器响应信息的时候(三次握手) NSLog(@"服务器响应"); self.receiveData = [NSMutableData data]; } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { //接收到服务器发送的数据 NSLog(@"服务器发送数据"); //每次接收到数据的时候都把数据拼接起来 [self.receiveData appendData:data]; } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { //接收数据完成 NSLog(@"数据接收完毕"); //数据请求完毕,对data进行解析 NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:self.receiveData options:NSJSONReadingMutableContainers error:nil]; NSLog(@"%@",dic); } - (IBAction)buttonBlock:(id)sender { //1.创建请求 NSString *str = @"http://api.douban.com/v2/movie/nowplaying?app_name=doubanmovie&client=e:iPhone4,1|y:iPhoneOS_6.1|s:mobile|f:doubanmovie_2|v:3.3.1|m:PP_market|udid:aa1b815b8a4d1e961347304e74b9f9593d95e1c5&alt=json&version=2&start=0&city=北京&apikey=0df993c66c0c636e29ecbb5344252a4a"; NSString *newStr = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url = [NSURL URLWithString:newStr]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60]; request.HTTPMethod = @"get"; //2.连接服务器 //参数1:请求 参数2:请求结束后,返回到哪个线程继续执行任务 参数3:请求结束,执行block中的代码 [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { //data是完整的请求完毕的数据 if (data != nil) { //对data的一个判断... NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; NSLog(@"%@",dic); } }]; } @end