同步: 请求数据时,其他的事情都做不了.
异步: 请求数据时还可以做其他的.
- (void)viewDidLoad {
[super viewDidLoad];
self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 100, 100, 100)];
self.imageView.backgroundColor = [UIColor orangeColor];
[self.view addSubview:self.imageView];
[_imageView release];
}
同步与异步的GET & POST 请求
- (IBAction)synGET:(id)sender {
NSLog(@"GET同步请求");
NSString *strURL = @"http://api.map.baidu.com/place/v2/search?query=银行®ion=大连&output=json&ak=6E823f587c95f0148c19993539b99295";
// 正常网址中不允许出现中文, 只能有26个字母的大小写 数字,和一些特殊的符号比如& % 等,如果遇到带中文出现的URL,首先要把它进行编码.
NSString *strENcode = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@",strENcode);
// 接下来, 当URL符合要求之后,就开始进行网络请求,网络请求分三步
//1.根据已经编码好的URL,创建一个NSURL
NSURL *url = [NSURL URLWithString:strENcode];
//2.发送一个请求.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//3.返回我们需要的数据,一个NSData对象.
/*
三个参数:
1.刚刚创建的请求
2.返回一个响应
3.错误信息
*/
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
// 对返回的数据,data进行JSON解析.
NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
for (NSMutableDictionary *temp in dic[@"results"]) {
NSLog(@"%@",temp[@"name"]);
}
}
- (IBAction)synPOST:(id)sender {
//大信加小信
NSLog(@"POST同步请求");
NSString *strURL = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";
NSURL *url = [NSURL URLWithString:strURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// 接下来是POST请求独有的部分
//把请求的方式首先设置成POST请求,默认是GET.
[request setHTTPMethod:@"POST"];
// 接下来需要把请求的内容放在request的body中.
NSString *bodyStr = @"date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213";
// 需要把请求部分的字符串变成NSData类型对象
NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
// 把bodyData放在request中.
[request setHTTPBody:bodyData];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"%@",dic);
for (NSMutableDictionary *temp in dic[@"news"]) {
NSLog(@"%@",temp[@"title"]);
}
}
- (IBAction)asynGET:(id)sender {
NSLog(@"GET异步请求");
NSString *strURL = @"http://img4.duitang.com/uploads/item/201207/28/20120728105310_jvAjW.thumb.600_0.jpeg";
NSURL *url = [NSURL URLWithString:strURL];
NSMutableURLRequest *requset = [NSMutableURLRequest requestWithURL:url];
// 前两步和之前一模一样,第三步出现变化,通过代理的方式进行操作.
[NSURLConnection connectionWithRequest:requset delegate:self];
}
//协议方法1
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
// 只要接收到服务器放回的响应信息,就会走这个方法,我们在这个方法中需要对接收数据的容器data进行初始化设置.
self.data = [NSMutableData data];
}
// 协议方法2
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
// 只要返回数据,就会走这个方法.
// 把每一次返回回来的data 全部都返回到这个容器里面. append时累加的意思.
[self.data appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
// 整个请求已经结束,需要把返回的data对imageview的image进行
self.imageView.image = [UIImage imageWithData:self.data scale:1];
}
#warning 同步和异步的请求在步骤上是一样的,只不过在使用NSURLConnection式的方法不同, 同步需要用NSData型的数据接受返回的用sendSyn的方法获得的数据. 而异步使用的代理方法.异步是基于
- (IBAction)asynPOST:(id)sender {
NSLog(@"异步POST");
NSString *strURL = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";
NSURL *url = [NSURL URLWithString:strURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
NSString *bodyStr = @"date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213";
NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:bodyData];
//3. 网络请求子线程里进行,请求下来的数据需要通过控件作为载体实现出来,需要把数据在主线程中显示,第二个参数就是指定把数据返回到那个线程.
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
// 参数data 就是我们请求的数据,接下来的数据解析就在block里完成.
NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
for (NSMutableDictionary *temp in dic[@"news"]) {
NSLog(@"%@",temp[@"summary"]);
}
}];
}
- (IBAction)blockGET:(id)sender {
NSLog(@"Block异步请求");
NSString *str = @"http://img4.duitang.com/uploads/item/201207/28/20120728105310_jvAjW.thumb.600_0.jpeg";
NSURL *url = [NSURL URLWithString:str];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
// 数据处理
self.imageView.image = [UIImage imageWithData:data];
}];
}
@end
#warning 总结一下网络请求的步骤: 1.根据网址的字符串,创建一个NSURL的对象;2.根据这个url对象创建一个请求; 3.发送请求,然后获取对象.NSURLConnection 同步和异步的请求方法选用有差别,其他都一样.
#warning POST 比 GET 请求request的方式不同, 改变setHTTPMethod变为POST,并且多加一个body.