*****
在电脑术语中,统一资源标识符(Uniform Resource Identifier,或URI)是一个用于标识某一互联网资源名称的字符串。 该种标识允许用户对任何(包括本地和互联网)的资源通过特定的协议进行交互操作。URI由包括确定语法和相关协议的方案所定义。
Web上可用的每种资源 -HTML文档、图像、视频片段、程序等 - 由一个通用资源标识符(Uniform Resource Identifier, 简称"URI")进行定位。
*****
1 REST Web Service 是一个使用HTTP并遵循REST原则的Web Service,使用URI来资源定位。Web Service支持的请求方式包括POST GET等。
Web Service应用层采用的是HTTP和HTTPS等传输协议。
GET方法是向指定的资源发出请求,发送的信息“显示”地跟在URL后面,GET方法应该只用于读取数据,它是不安全的。
POST方法是向指定资源提交数据,请求服务器进行处理,数据被包含在请求体中,是安全的。
GET POST方法与同步请求与异步请求无关。
2 同步GET请求方法
iOS SDK 为HTTP请求提供了同步和异步请求两种API,而且还可以使用GET和POST等请求方法。
创建URL(3步走)-创建request-发送请求接受数据-解析数据
/* * 开始请求Web Service */ -(void)startRequest { 指定请求的URL ?后面是请求参数,一般是开发者提供 NSString *strURL = [[NSString alloc] initWithFormat:@"http://www.51work6.com/service/mynotes/WebService.php?email=%@&type=%@&action=%@",@"<你的51work6.com用户邮箱>",@"JSON",@"query"]; 将字符串编码为URL字符串 因为URL中不能有特殊字符 strURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url = [NSURL URLWithString:strURL]; 创建请求 NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; 同步请求发送并接受数据 异步的方法,发送同步的请求 NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; NSLog(@"请求完成..."); 解析数据 NSDictionary *resDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; [self reloadView:resDict]; } //重新加载表视图 -(void)reloadView:(NSDictionary*)res { NSNumber *resultCode = [res objectForKey:@"ResultCode"]; if ([resultCode integerValue] >=0)说明在服务器端操作成功 { self.objects = [res objectForKey:@"Record"]; [self.tableView reloadData]; } else { 意味着ResultCode=-1; NSString *errorStr = [resultCode errorMessage];NSNumber分类定义的方法,用于区分错误 UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"错误信息" message:errorStr delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil]; [alertView show]; }
3 异步GET请求方法
NSURLConnection NSURLConnectiongDelegate 在请求的不同阶段会调用不同方法
方法:connection:didReceiveData:请求成功并建立连接
connection:didFailWithError:加载数据出现异常
connectionDidFinishLoading:成功完成数据加载
创建链接发送请求调用代理方法-接受数据-解析数据
/* * 开始请求Web Service */ -(void)startRequest { NSString *strURL = [[NSString alloc] initWithFormat:@"http://www.51work6.com/service/mynotes/WebService.php?email=%@&type=%@&action=%@",@"<你的51work6.com用户邮箱>",@"JSON",@"query"]; strURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url = [NSURL URLWithString:strURL]; NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; 创建链接发送请求 NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; if (connection) { self.datas = [NSMutableData new];准备接收数据 } } #pragma mark- NSURLConnection 回调方法 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [self.datas appendData:data]; } -(void) connection:(NSURLConnection *)connection didFailWithError: (NSError *)error { NSLog(@"%@",[error localizedDescription]); } - (void) connectionDidFinishLoading: (NSURLConnection*) connection { NSLog(@"请求完成..."); NSDictionary* dict = [NSJSONSerialization JSONObjectWithData:self.datas options:NSJSONReadingAllowFragments error:nil]; [self reloadView:dict]; }
4 POST请求方法(异步)
关键是用NSMutableURLRequest类代替NSURLRequest
创建服务器URL-创建请求体-将请求体编码为请求参数-创建可变请求对象NSMutableURLRequest-创建链接调用代理方法
/* * 开始请求Web Service */ -(void)startRequest { NSString *strURL = @"http://www.51work6.com/service/mynotes/WebService.php"; strURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url = [NSURL URLWithString:strURL]; 请求体 NSString *post = [NSString stringWithFormat:@"email=%@&type=%@&action=%@", @"<你的51work6.com用户邮箱>",@"JSON",@"query"]; 请求参数 NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding]; 创建请求设置内容 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request setHTTPMethod:@"POST"]; [request setHTTPBody:postData]; NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; if (connection) { self.datas = [NSMutableData new]; } } #pragma mark- NSURLConnection 回调方法 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [self.datas appendData:data]; } -(void) connection:(NSURLConnection *)connection didFailWithError: (NSError *)error { NSLog(@"%@",[error localizedDescription]); } - (void) connectionDidFinishLoading: (NSURLConnection*) connection { NSLog(@"请求完成..."); NSDictionary* dict = [NSJSONSerialization JSONObjectWithData:self.datas options:NSJSONReadingAllowFragments error:nil]; [self reloadView:dict]; }
5 调用REST Web Service的插入 修改 删除方法
1)插入
使用POST请求传入数据再使用回调方法获取已经改好的数据
* 开始请求Web Service */ -(void)startRequest { //准备参数 NSDate *date = [NSDate new]; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"yyyy-MM-dd"]; 当前的系统日期 NSString *dateStr = [dateFormatter stringFromDate:date]; //设置参数 NSString *post = [NSString stringWithFormat:@"email=%@&type=%@&action=%@&date=%@&content=%@", @"<你的51work6.com用户邮箱>",@"JSON",@"add",dateStr,self.txtView.text]; NSString *strURL = @"http://www.51work6.com/service/mynotes/WebService.php"; strURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url = [NSURL URLWithString:strURL]; NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request setHTTPMethod:@"POST"]; [request setHTTPBody:postData]; NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; if (connection) { _datas = [NSMutableData new]; } } #pragma mark- NSURLConnection 回调方法 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [self.datas appendData:data]; } -(void) connection:(NSURLConnection *)connection didFailWithError: (NSError *)error { NSLog(@"%@",[error localizedDescription]); } - (void) connectionDidFinishLoading: (NSURLConnection*) connection { NSLog(@"请求完成..."); NSDictionary* dict = [NSJSONSerialization JSONObjectWithData:self.datas options:NSJSONReadingAllowFragments error:nil]; NSString *message = @"操作成功。"; NSNumber *resultCodeObj = [dict objectForKey:@"ResultCode"]; if ([resultCodeObj integerValue] < 0) { message = [resultCodeObj errorMessage]; } UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示信息" message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil]; [alertView show]; }
2)删除
删除与查询是在同一个视图控制器中,需要做一些判断。
将请求Web Service的startRequest方法放到这里,可以保证每次改视图出现时都会请求服务器返回数据-(void)viewWillAppear:(BOOL)animated { [super viewWillAppear:YES]; action = QUERY;自定义枚举 [self startRequest]; }
删除方法是在表视图数据源方法实现的:
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { return YES; } - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { //删除数据 action = REMOVE; deleteRowId = indexPath.row; 开始在数据库中删除疏浚 [self startRequest]; } else if (editingStyle == UITableViewCellEditingStyleInsert) { } }
startRequest方法中需要判断请求动作标示
/* * 开始请求Web Service */ -(void)startRequest { NSString *strURL = @"http://www.51work6.com/service/mynotes/WebService.php"; strURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url = [NSURL URLWithString:strURL]; NSString *post; if (action == QUERY) {//查询处理 post = [NSString stringWithFormat:@"email=%@&type=%@&action=%@", @"<你的51work6.com用户邮箱>",@"JSON",@"query"]; } else if (action == REMOVE) {//删除处理 NSMutableDictionary* dict = self.objects[deleteRowId]; post = [NSString stringWithFormat:@"email=%@&type=%@&action=%@&id=%@", @"<你的51work6.com用户邮箱>",@"JSON",@"remove",[dict objectForKey:@"ID"]]; } NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request setHTTPMethod:@"POST"]; [request setHTTPBody:postData]; NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; if (connection) { self.datas = [NSMutableData new]; } }
connectionDidFinishLoading:也要判断标示
- (void) connectionDidFinishLoading: (NSURLConnection*) connection { NSLog(@"请求完成..."); // NSString* str = [[NSString alloc] initWithData:self.datas encoding:NSUTF8StringEncoding]; // NSLog(str); NSDictionary* dict = [NSJSONSerialization JSONObjectWithData:self.datas options:NSJSONReadingAllowFragments error:nil]; if (action == QUERY) {//查询处理 [self reloadView:dict]; } else if (action == REMOVE) {//删除处理 NSString *message = @"操作成功。"; NSNumber *resultCodeObj = [dict objectForKey:@"ResultCode"]; if ([resultCodeObj integerValue] < 0) { message = [resultCodeObj errorMessage]; } UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示信息" message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil]; [alertView show]; //重新查询 action = QUERY; [self startRequest]; } }