//
// ViewController.m
// UI14_GET-POST
//
// Created by dllo on 15/8/17.
// Copyright (c) 2015年 zhozhicheng. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()<NSURLConnectionDataDelegate>
- (IBAction)synGET:(id)sender;
- (IBAction)synPOST:(id)sender;
- (IBAction)asynGET:(id)sender;
- (IBAction)asynPOST:(id)sender;
- (IBAction)block:(id)sender;
@property(nonatomic,retain)UIImageView *imageView;
@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(200, 100, 150, 150)];
self.imageView.backgroundColor =[UIColor cyanColor];
[self.view addSubview:self.imageView];
[_imageView release];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)synGET:(id)sender {
// NSLog(@"GET同步请求");
NSString *strURL =@"http://api.map.baidu.com/place/v2/search?query=银行®ion=大连&output=json&ak=6E823f587c95f0148c19993539b99295";
//一个正常的URL地址是不允许有中文的,只能有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对象
//三个参数:第一个参数是刚刚创建的请求,第二个是返回的一个响应,第三个是错误信息
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];
NSMutableArray *arr = dic[@"results"];
for (NSDictionary *dic in arr) {
NSLog(@"%@",dic[@"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];
//json解析
NSMutableDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"%@",dic);
}
- (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 *request =[NSMutableURLRequest requestWithURL:url];
//前两步和之前还是一样,第三步出现变化,通过代理的方式进行异步操作
[NSURLConnection connectionWithRequest:request delegate:self];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
//只要接收到服务器返回的响应信息,就会走这个方法,我们在这个方法里需要对接收数据的容器data进行初始化的设置
self.data = [NSMutableData data];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
//只要他返回数据,就会走这个方法
//append是累加的意思
[self.data appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//到这,整个请求已经结束,需要把返回的DATA对imageView的image进行赋值
self.imageView.image = [UIImage imageWithData:self.data];
}
#warning 同步和异步GET请求在步骤上完全相同,只是在第三步同步使用的是sendSyn方法,同步使用的是代理的方法,异步是基于同步进行操作
- (IBAction)asynPOST:(id)sender {
NSLog(@"POST异步");
NSString *strURL =@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";
//1.创建NSUrl
NSURL *url = [NSURL URLWithString:strURL];
//2.请求
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url];
//3.request请求方式
[request setHTTPMethod:@"POST"];
NSString *bodyStr = @"date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213";
NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
//添加到request
[request setHTTPBody:bodyData];
//
//网络请求在子线程里进行请求,请求下来的数据需要通过控件作为载体实现出来,需要把数据在主线程里显示,第二个参数就是指定把数据返回到那个线程
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//参数data就是我们请求下来的数据,接下来数据的解析就在block中进行操作
//json解析
NSMutableDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"%@",dic);
}];
}
- (IBAction)block:(id)sender {
NSLog(@"GET异步通过block的方式");
NSString *str =@"http://img4.duitang.com/uploads/item/201207/28/20120728105310_jvAjW.thumb.600_0.jpeg";
//1.创建一个NSURL
NSURL *url =[NSURL URLWithString:str];
//2.发送一个请求
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url];
//3.异步
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//数据处理依旧在block中进行
self.imageView.image = [UIImage imageWithData:data];
}];
}
@end
#warning 总结一下网络请求的步骤:1.根据网址的字符串,创建一个NSURL对象,2.根据这个url对象,创建一个请求,3.发送请求,然后获取请求对象,同步和异步的区别就是请求方法选用有差别,其他都一样
#warning POST就是比GET多一个,需要request添加一个body