首页 > 代码库 > ASIHTTPRequest框架使用总结系列之阿堂教程2(同步请求)
ASIHTTPRequest框架使用总结系列之阿堂教程2(同步请求)
从本篇开始,阿堂结合一些具体代码来说明。在ASIHTTPRequest框架中,与http请求相关的类有ASIHTTPRequest 和 ASIFormDataRequest,其中最常用的是 ASIHTTPRequest ,ASIFormDataRequest 是ASIHTTPRequest 的子类,可以发送html类似的表单数据,也可以上传数据,默认采用其它httpy请求方式。它们都可以进行异步或同步请求。
-(void)startRequest
{
NSString *strURL = [[NSString alloc]initWithFormat:@"http://www.crazyit.com/service/mynotes/webservice.php?email=%@&type=%@&action=%@",@"heyitang@qq.com",@"JSON",@"query"];
NSURL *url = [NSURL URLWithString:[strURL URLEncodedString]];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request startSynchronous]; //同步请求
NSLog(@"请求完成...");
NSError *error = [request error];
//如果错误对象不为空,说明这个请求过程出现了错误
if (!error) {
//NSString *response = [request responseString];
NSData *data = [request responseData];
//返回值为NSData,这种类型适合 NSJSONSerialization解析
//如果想返回字符串,可以用 NSString *data = [request responseString];
NSDictionary *resDict = [NSJSONSerialization JSONObjectWithData:dataoptions:NSJSONReadingAllowFragments error:nil];
[self reloadView:resDict];
}
}
//重新加载表视图
-(void)reloadView:(NSDictionary*)res
{
NSNumber *resultCodeObj = [res objectForKey:@"ResultCode"];
if ([resultCodeObj integerValue] >=0)
{
self.listData = [res objectForKey:@"Record"];
[self.tableView reloadData];
} else {
NSString *errorStr = [resultCodeObj errorMessage];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"错误信息"
message:errorStr
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles: nil];
[alertView show];
}
}
-(void)startRequest
{
NSString *strURL = @"http://www.crazyit.com/service/mynotes/webservice.php";
NSURL *url = [NSURL URLWithString:[strURL URLEncodedString]];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:@"heyitang@qq.com" forKey:@"email"];
[request setPostValue:@"JSON" forKey:@"type"];
[request setPostValue:@"query" forKey:@"action"];
[request startSynchronous];
NSLog(@"请求完成...");
NSError *error = [request error];
if (!error) {
//NSString *response = [request responseString];
NSData *data = [request responseData];
NSDictionary *resDict = [NSJSONSerialization JSONObjectWithData:dataoptions:NSJSONReadingAllowFragments error:nil];
[self reloadView:resDict];
}
}
//重新加载表视图
-(void)reloadView:(NSDictionary*)res
{
NSNumber *resultCodeObj = [res objectForKey:@"ResultCode"];
if ([resultCodeObj integerValue] >=0)
{
self.listData = [res objectForKey:@"Record"];
[self.tableView reloadData];
} else {
NSString *errorStr = [resultCodeObj errorMessage];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"错误信息"
message:errorStr
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles: nil];
[alertView show];
}
}
ASIHTTPRequest框架使用总结系列之阿堂教程2(同步请求)