Get和post网络请求
2016-01-03 11:54
543 查看
一般block用的比较多
下面是实例
Movie.h
Movie.m
ViewController.m
#import "ViewController.h" @interface ViewController ()<NSURLSessionDelegate> - (IBAction)asynAction:(id)sender; - (IBAction)synProtocolGET:(id)sender; - (IBAction)synProtocolPOST:(id)sender; - (IBAction)synGETblock:(id)sender; - (IBAction)synPOSTblock:(id)sender; @property(nonatomic,retain)UIImageView *imageView; //用来接受返回的data数据 @property(nonatomic,retain)NSMutableData *data; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. self.imageView=[[UIImageView alloc] initWithFrame:CGRectMake(100, 500, 200, 200)]; [self.view addSubview:self.imageView]; self.imageView.backgroundColor=[UIColor cyanColor]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (IBAction)asynAction:(id)sender { NSString *urlStr=@"http://img4.duitang.com/uploads/item/201207/28/20120728105310_jvAjW.thumb.600_0.jpeg"; NSURL *url=[NSURL URLWithString:urlStr]; NSData *data=[NSData dataWithContentsOfURL:url]; // NSLog(@"%@",data); // NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; // NSLog(@"%@",dic); self.imageView.image=[UIImage imageWithData:data]; } //NSURLSession是session的代理方法 //NSURLSession的使用和NSURLConnection的使用基本相似,他在7.0以后出现,主要是为了提高NSURLConnection的性能,它提供下载等功能 //Session可以通过协议和block两种方式进行使用 - (IBAction)synProtocolGET:(id)sender { NSString *urlStr=@"http://api.map.baidu.com/place/v2/search?query=银行®ion=大连&output=json&ak=6E823f587c95f0148c19993539b99295"; //url由字母和数字,特殊符号,比如/,&,?,=,$组成,所以一般的url里是没有汉字的,所有的汉字在请求的时候需要给他进行转码 //ios9.0以后,转码的方法也发生了变化,采用字符集合的方式对网址进行转码操作 urlStr=[urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:urlStr]]; // NSLog(@"%@",urlStr); // NSString ->NSURL NSURL *url=[NSURL URLWithString:urlStr]; //创建NSURLSession对象 NSURLSession *session=[NSURLSession sessionWithConfiguration: [NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]]; //创建一个请求对象 NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url]; //创建一个Session的tast任务对象 NSURLSessionDataTask *task=[session dataTaskWithRequest:request]; //任务执行 [task resume]; } //完成网络请求,一般使用3个协议方法 //694行 - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler{ //方法会把请求的服务器响应信息返回,就是response,这里面能查看响应码status code,200是请求成功,404没有像找到对应的页面,response可以查看这个网址是否在正确的信息 // NSLog(@"%@",response); //服务器响应之后,需要允许服务器响应,才可以继续接受从服务器返回的数据,方法里第四个参数block就是做这个功能的 completionHandler(NSURLSessionResponseAllow); //当手机与服务器都允许之后,初始化self.data,用来接收数据 self.data=[NSMutableData data]; } //用来接收数据的协议方法,在接收数据的过程中,这个方法会被调用多次,直到数据全部接受完成 //728行 - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data{ //只要执行这个方法,会把数据data返回,我们在这个方法里需要做的,就是把方法data全部进行累加,等到最后一个数据请求下来之后,所有数据累加到一起,完成请求过程 [self.data appendData:data]; } //675行 //这个协议方法一般会在完成请求或者请求失败时触发,区分的话就是error,如果请求成功,error是没有值得 - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(nullable NSError *)error{ NSLog(@"%@",error); if (error==nil) { NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:self.data options:0 error:nil]; NSLog(@"%@",dic); }else{ NSLog(@"请求失败"); } } - (IBAction)synProtocolPOST:(id)sender { NSString *strURL=@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&a 4000 mp;startRecord=1&len=15&udid=1234567890&terminalType=Iphone&cid=213"; NSURL *url=[NSURL URLWithString:strURL]; NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url]; //设置当前请求方式 //请求方式默认是GET //PUT,DELETE [request setHTTPMethod:@"POST"]; NSString *bodyStr=@"username=daka&pwd=123"; NSData *bodyData=[bodyStr dataUsingEncoding:NSUTF8StringEncoding]; //加到请求中 [request setHTTPBody:bodyData]; } - (IBAction)synGETblock:(id)sender { NSString *strURL=@"http://project.lanou3g.com/teacher/yihuiyun/lanouproject/movielist.php"; NSURL *url=[NSURL URLWithString:strURL]; NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url]; //创建一个session对象 NSURLSession *session=[NSURLSession sharedSession]; //根据session对象,创建一个任务task NSURLSessionTask *task=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { NSLog(@"%@",response); NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; NSLog(@"%@",dic); }]; //任务必须手动去执行 [task resume]; } - (IBAction)synPOSTblock:(id)sender { NSString *strURL=@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=15&udid=1234567890&terminalType=Iphone&cid=213"; NSURL *url=[NSURL URLWithString:strURL]; NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url]; [request setHTTPMethod:@"POST"]; NSString *bodyStr=@"username=daka&pwd=123"; NSData *bodyData=[bodyStr dataUsingEncoding:NSUTF8StringEncoding]; [request setHTTPBody:bodyData]; NSURLSession *session=[NSURLSession sharedSession]; NSURLSessionTask *task=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; NSLog(@"%@",dic); }]; [task resume]; }
下面是实例
Movie.h
#import <Foundation/Foundation.h> @interface Movie : NSObject @property(nonatomic,copy)NSString *movieName; @end
Movie.m
#import "Movie.h" @implementation Movie -(void)setValue:(id)value forUndefinedKey:(NSString *)key{ } @end
ViewController.m
#import "ViewController.h" #import "Movie.h" @interface ViewController ()<UITableViewDataSource,UITableViewDelegate> @property(nonatomic,retain)NSMutableArray *arr; @property(nonatomic,retain)UITableView *tableView; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. self.tableView=[[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain]; [self.view addSubview:self.tableView]; self.tableView.delegate=self; self.tableView.dataSource=self; [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"reuse"]; [self createData]; NSLog(@"%@",NSHomeDirectory()); } -(void)createData{ NSString *strURL=@"http://project.lanou3g.com/teacher/yihuiyun/lanouproject/movielist.php"; NSURL *url=[NSURL URLWithString:strURL]; NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url]; // [request setHTTPMethod:@"POST"]; // NSString *bodyStr=@"username=daka&pwd=123"; // NSData *bodyData=[bodyStr dataUsingEncoding:NSUTF8StringEncoding]; // [request setHTTPBody:bodyData]; NSURLSession *session=[NSURLSession sharedSession]; NSURLSessionTask *task=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { //数据在子线程里请求,但是还是需要在主线程里 显示,所以需要把请求到的放到主线程里显示 dispatch_queue_t mainQuenue=dispatch_get_main_queue(); dispatch_async(mainQuenue, ^{ //在这里面写数据的处理 NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; self.arr=[NSMutableArray array]; for (NSDictionary *temp in dic[@"result"]) { Movie *movie=[[Movie alloc] init]; [movie setValuesForKeysWithDictionary:temp]; [self.arr addObject:movie]; } //刷新 [self.tableView reloadData]; }); }]; [task resume]; } -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ return self.arr.count; } -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"reuse" forIndexPath:indexPath]; Movie *movie=self.arr[indexPath.row]; cell.textLabel.text=movie.movieName; return cell; }