使用苹果提供的NSURLConnection和NSURLRequest网络请求API固然能解决我们大部的Web Service请求,但是使用起来不是很简洁,又不是很方便。因此做开发时我们一般用第三方的框架,目前主要有三种框架:ASIHTTPRequest、AFNetworking和MKNetworkKIt。
在这三个框架中,ASI是最早设计的框架,它功能强大但不支持ARC,现在原作者已经停止更新了。AFNETWorking是之后出现的框架,比ASI更加简单。MKNetworkKit的设计思想来源于ASI和AF,它结合了这两个框架的共同特点,并增加了一些新特性,但现在用它的人还比较少。在这里主要写一下AFNetworking。本人也是新人,理解的不够深刻,希望得到大家的指导。
现在AFNetworking有两个版本 1.x 和最新的2.0,如果项目需要兼容ios5.0,那么就需要使用1.x版本,因为2.0仅支持ios6以上。
1.post请求
//1.x
//post另外一种方法
client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://192.168.1.198/Dshequ/countdown.php"]];
[client postPath:nil parameters:@{@"phone": self.telephoneNumber.text,@"code":yanzheng} success:^(AFHTTPRequestOperation *operation, id responseObject){
NSLog(@"success obj 9898 %@",responseObject);
html = operation.responseString;
NSLog(@"第一次返回的字符串为:%@",html);
int flg=[html intValue];
NSLog(@"转换成int:%d",flg);
if (flg==0) {
}else
{
isZhuce = NO;
NSLog(@"该用户还没有注册!");
switch (flg) {
//账号好没有注册
case -1:
break;
default:
break;
}
}
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"faild , error == %@ ", error);
}];
//2.0
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; NSDictionary *parameters = @{@"foo": @"bar"}; [manager POST:@"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"JSON: %@", responseObject); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"Error: %@", error); }];
2.get请求
//1.x
AFHTTPClient *bClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://192.168.1.198/Dshequ/countdown.php"]];
[bClient getPath:nil parameters:nil success:^(AFHTTPRequestOperation *operation,id responseObject)
{
NSLog(@"response description:%@",[responseObject description]);
NSLog(@"operation:%@",operation.responseString);
}
failure:^(AFHTTPRequestOperation *operation,NSError *error)
{
NSLog(@"error description:%@",[error description]);
}];
}
//2.0
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; [manager GET:@"http://example.com/resources.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"JSON: %@", responseObject); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"Error: %@", error); }];
}
}