#import "MainViewController.h"
@interface MainViewController ()<NSURLConnectionDataDelegate>
@property (nonatomic, retain)UIImageView *imageView;
@property (nonatomic, retain)NSMutableData *data;// 可变数据 Data 用于拼接每次接受来的数据块
@end
@implementation MainViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 20, 280, 280)];
self.imageView.backgroundColor = [UIColor redColor];
[self.view addSubview:self.imageView];
[self.imageView release];
UIButton *button1 = [UIButton buttonWithType:UIButtonTypeSystem];
button1.frame = CGRectMake(20, 320, 120, 40);
button1.backgroundColor = [UIColor brownColor];
[button1 setTitle:@"同步 GET" forState:UIControlStateNormal];
[button1 addTarget:self action:@selector(buttonClicked1:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button1];
UIButton *button2 = [UIButton buttonWithType:UIButtonTypeSystem];
button2.frame = CGRectMake(180, 320, 120, 40);
button2.backgroundColor = [UIColor brownColor];
[button2 setTitle:@"同步 POST" forState:UIControlStateNormal];
[button2 addTarget:self action:@selector(buttonClicked2:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button2];
UIButton *button3 = [UIButton buttonWithType:UIButtonTypeSystem];
button3.frame = CGRectMake(20, 400, 120, 40);
button3.backgroundColor = [UIColor brownColor];
[button3 setTitle:@"异步 GET" forState:UIControlStateNormal];
[button3 addTarget:self action:@selector(buttonClicked3:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button3];
UIButton *button4 = [UIButton buttonWithType:UIButtonTypeSystem];
button4.frame = CGRectMake(180, 400, 120, 40);
button4.backgroundColor = [UIColor brownColor];
[button4 setTitle:@"异步 POST" forState:UIControlStateNormal];
[button4 addTarget:self action:@selector(buttonClicked4:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button4];
}
- (void)buttonClicked1:(UIButton *)button
{
// 同步GET
// 1.拼接网络地址
NSString *str = @"http://cdn.gq.com.tw.s3-ap-northeast-1.amazonaws.com/userfiles/images_A1/6954/2011100658141857.jpg"
;
// 2.将地址转化为URL对象
NSURL *url = [NSURL URLWithString:str];
// 3. 创建一个请求(request)
// 参数1: 请求地址(NSURL)
// 参数2:给请求选择一个缓存策略
// 参数3: 请求超时时间
NSMutableURLRequest *requset = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
// 4. 给请求设置 请求方式
[requset setHTTPMethod:@"GET"];
// 5. 将请求发送给服务器
// 同步连接
// 参数1:请求(request)
// 参数2:响应信息
// 参数3:错误信息
// 同步连接的方法 会一直等待 数据完整接受之后才继续执行
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:requset returningResponse:&response error:&error];
//在这里获得的是完整的 data数据
NSLog(@"服务器响应信息:%@", response);
// 使用NSData数据
UIImage *image = [UIImage imageWithData:data];
self.imageView.image = image;
NSLog(@"%@", NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES));
}
-(void)dealloc
{
[_data release];
[_imageView release];
[super dealloc];
}
- (void)buttonClicked2:(UIButton *)button
{
// 同步POST
NSString *str = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";
NSURL *url = [NSURL URLWithString:str];
// 创建请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
// 设置请求方式
[request setHTTPMethod:@"POST"];
// 产生一个body
NSString *bodyStr = @"date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213";
NSData *data = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
// 设置post请求 附带的数据
[request setHTTPBody:data];
// 同步连接 获取内容
NSURLResponse *response = nil;
NSData *dataBack = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSLog(@"%@", response);
// 测试返回数据内容
NSString *result = [[NSString alloc] initWithData:dataBack encoding:NSUTF8StringEncoding];
NSLog(@"%@", result);
}
- (void)buttonClicked3:(UIButton *)button
{
// 异步
// 1. 产生请求
NSString *str = @"http://pic13.nipic.com/20110313/2686941_211532129160_2.jpg";
NSURL *url = [NSURL URLWithString:str];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:@"GET"];
// 2.建立连接
// 异步联接 不会卡死界面
// 参数1:设定好的请求
// 参数2:设定网络请求的代理人
[NSURLConnection connectionWithRequest:request delegate:self];
}
// 当收到服务器的响应信息 的时候 调用
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// 当每次需要接受新的数据的时候 初始化data属性
NSLog(@"%s", __FUNCTION__);
self.data = [NSMutableData data];
}
// 当收到服务器发送来的 data数据块 的时候 调用
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(@"%s", __FUNCTION__);
[self.data appendData:data];
}
// 当数据接受完毕 的时候 调用
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// 调用这个方法 说明 self.data属性已经是一个完整的数据
NSLog(@"%s", __FUNCTION__);
UIImage *image = [UIImage imageWithData:self.data];
self.imageView.image = image;
}
- (void)buttonClicked4:(UIButton *)button
{
// 异步POST
NSString *str = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";
NSURL *url = [NSURL URLWithString:str];
// 创建请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
// 设置请求方式
[request setHTTPMethod:@"POST"];
// 设置body
NSString *bodyStr = @"date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213";
NSData *data = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
// 设置post请求 附带的数据
[request setHTTPBody:data];
// 2. 连接
// block 基础上的异步连接
// 参数1:请求
// 参数2:返回主线程
// 参数3:
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
// 当异步联接完毕 而且 请求但完整的数据(参数data)之后 才执行这个块的内容
// 在这个块中 写处理数据的代码 (解析/转化为image/音频/视频)
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"%@", dic);
}];
}