#import <UIKit/UIKit.h>
@interface RootViewController : UIViewController<NSURLConnectionDataDelegate>
{
UIImageView *imageV;
//创建可变data接收下载的数据
NSMutableData *myData;
}
@end
// ***********************************************************//
#import "RootViewController.h"
@interface RootViewController ()
@end
@implementation RootViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationItem.title = @"网络编程";
/*
从服务器拿数据,可以用get 也可以用post,get请求完全透明,暴露在网址中,而post请求,有body体,我们可以将需要保密的东西放在body里面
例如从服务器下载一首歌
get:www.getmusic-name = @"lalala"....
post:www.getmusic...body = (里面东西看不见)
*/
/*
向服务器发送数据
get 要发送的内容,还是暴露在网址里面(其实就只能发字符串)并且大小要求小于255字节
post 要发送的内容放在body里面 看不见,有保密特性,大小可以超过1G
*/
imageV = [[UIImageView alloc] initWithFrame:CGRectMake(40, 120, self.view.frame.size.width - 80, 400)];
imageV.backgroundColor = [UIColor whiteColor];
[self.view addSubview:imageV];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(10, 50, 80, 40);
[button setTitle:@"同步GET" forState:UIControlStateNormal];
button.backgroundColor = [UIColor blackColor];
button.showsTouchWhenHighlighted = YES;
button.titleLabel.font = [UIFont systemFontOfSize:16];
[self.view addSubview:button];
[button addTarget:self action:@selector(tongBuGet) forControlEvents:UIControlEventTouchUpInside];
UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom];
button2.frame = CGRectMake(100, 50, 80, 40);
[button2 setTitle:@"同步POST" forState:UIControlStateNormal];
button2.backgroundColor = [UIColor blackColor];
button2.showsTouchWhenHighlighted = YES;
button2.titleLabel.font = [UIFont systemFontOfSize:16];
[self.view addSubview:button2];
[button2 addTarget:self action:@selector(tongBuPost) forControlEvents:UIControlEventTouchUpInside];
UIButton *button3 = [UIButton buttonWithType:UIButtonTypeCustom];
button3.frame = CGRectMake(190, 50, 80, 40);
[button3 setTitle:@"异步block" forState:UIControlStateNormal];
button3.backgroundColor = [UIColor blackColor];
button3.showsTouchWhenHighlighted = YES;
button3.titleLabel.font = [UIFont systemFontOfSize:16];
[self.view addSubview:button3];
[button3 addTarget:self action:@selector(yiBuBlock) forControlEvents:UIControlEventTouchUpInside];
UIButton *button4 = [UIButton buttonWithType:UIButtonTypeCustom];
button4.frame = CGRectMake(280, 50, 80, 40);
[button4 setTitle:@"异步代理" forState:UIControlStateNormal];
button4.backgroundColor = [UIColor blackColor];
button4.showsTouchWhenHighlighted = YES;
button4.titleLabel.font = [UIFont systemFontOfSize:16];
[self.view addSubview:button4];
[button4 addTarget:self action:@selector(yiBuDelegate) forControlEvents:UIControlEventTouchUpInside];
}
//异步代理 借助代理方法下载图片
- (void)yiBuDelegate
{
NSString *str = @"http://imgsrc.baidu.com/forum/w%3D580/sign=fdd4c315b9014a90813e46b599763971/b962d4bf6c81800afa1bf5a9b13533fa838b4751.jpg";
NSURL *url = [NSURL URLWithString: str];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
request.HTTPMethod = @"GET";
//借助代理
[NSURLConnection connectionWithRequest: request delegate: self];
}
#pragma mark -- NSURLConnection的代理方法
//1、收到服务器响应信息
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
//初始化data
myData = [NSMutableData data];
}
//2、收到数据
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
//收到的数据 加到可变data里面
[myData appendData: data];
}
//3、下载失败
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"%@",error);
}
//4、下载完成
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
UIImage *image = [UIImage imageWithData: myData];
imageV.image = image;
}
//异步block下载图片
- (void)yiBuBlock
{
NSString *str = @"http://b.hiphotos.baidu.com/image/h%3D360/sign=ba4fae7036d12f2ed105a8667fc3d5ff/94cad1c8a786c917be9d9d9ec93d70cf3ac757ff.jpg";
NSURL *url = [NSURL URLWithString: str];
//创建请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval: 60];
//设置请求方式
request.HTTPMethod = @"GET";
//发送请求 当程序执行到这一行时,并不会停止,继续执行下面的代码,当下载结束之后,再回来执行block内部代码,是异步请求方式,不会造成程序假死现象
// NSOperationQueue mainQueue 主线程
[NSURLConnection sendAsynchronousRequest: request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
// 下载结束走这里
UIImage *image = [UIImage imageWithData: data];
imageV.image = image;
}];
}
//同步下载网易新闻
- (void)tongBuPost
{
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];
//设置请求方式
request.HTTPMethod = @"POST";
//设置body
NSString *bodyStr = @"date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213";
//将字符串转成NSData
NSData *data = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];//编码格式
request.HTTPBody = data;
//发送请求
NSURLResponse *response = nil;
NSError *error = nil;
NSData * dataResult = [NSURLConnection sendSynchronousRequest:request returningResponse: &response error: &error];
//将data转成字符串打印
NSString *resultStr = [[NSString alloc] initWithData: dataResult encoding:NSUTF8StringEncoding];
NSLog(@"%@",resultStr);
}
//同步下载图片
- (void)tongBuGet
{
NSString *str = @"http://h.hiphotos.baidu.com/image/h%3D360/sign=f44985e6cf80653864eaa215a7dca115/8cb1cb1349540923ba0e63d69758d109b3de4936.jpg";
//将字符串转成网址
NSURL *url = [NSURL URLWithString: str];
//创建一个请求 参数1:网址 参数2:缓存策略 参数3:超时时间
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval: 60];//超过60秒请求失败 post 3.0 始终是240秒
//设置请求方式(默认就是GET,要大写)
request.HTTPMethod = @"GET";
//发送请求 参数1:请求 参数2:服务器的相应信息 参数3:错误信息
//创建相应信息和错误信息
NSURLResponse *response = nil;
NSError *error = nil;
//同步请求 当程序执行的这一行 会出现假死状态,直到下载结束之后才会继续往下执行下面的代码
NSData *data = [NSURLConnection sendSynchronousRequest: request returningResponse: &response error: &error];
UIImage *image = [UIImage imageWithData: data];
imageV.image = image;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end