网络请求
新建一个工程
.h文件中
{
UIImageView *imagev;
}
@property(nonatomic,strong)NSMutableData *myData;//接收下载的数据
.m文件中
- (void)viewDidLoad {
[super viewDidLoad];
UIButton *getButton =[UIButton buttonWithType:UIButtonTypeCustom];
getButton.frame = CGRectMake(30, 40, 200, 40);
[self.view addSubview:getButton];
[getButton setTitle:@"同步GET" forState:UIControlStateNormal];
[getButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
getButton.layer.borderColor = [UIColor greenColor].CGColor;
getButton.layer.borderWidth = 0.3;
[getButton addTarget:self action:@selector(synchronizeGet) forControlEvents:UIControlEventTouchUpInside];
UIButton *postButton =[UIButton buttonWithType:UIButtonTypeCustom];
postButton.frame = CGRectMake(30, 90, 200, 40);
[self.view addSubview:postButton];
[postButton setTitle:@"同步POST" forState:UIControlStateNormal];
[postButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
postButton.layer.borderColor = [UIColor greenColor].CGColor;
postButton.layer.borderWidth = 0.3;
[postButton addTarget:self action:@selector(synchronizePost) forControlEvents:UIControlEventTouchUpInside];
UIButton *dailiButton =[UIButton buttonWithType:UIButtonTypeCustom];
dailiButton.frame = CGRectMake(30, 140, 200, 40);
[self.view addSubview:dailiButton];
[dailiButton setTitle:@"异步代理" forState:UIControlStateNormal];
[dailiButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
dailiButton.layer.borderColor = [UIColor greenColor].CGColor;
dailiButton.layer.borderWidth = 0.3;
[dailiButton addTarget:self action:@selector(yibuDelegata) forControlEvents:UIControlEventTouchUpInside];
UIButton *blockButton =[UIButton buttonWithType:UIButtonTypeCustom];
blockButton.frame = CGRectMake(30, 190, 200, 40);
[self.view addSubview:blockButton];
[blockButton setTitle:@"异步block" forState:UIControlStateNormal];
[blockButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
blockButton.layer.borderColor = [UIColor greenColor].CGColor;
blockButton.layer.borderWidth = 0.3;
[blockButton addTarget:self action:@selector(yibuBlock) forControlEvents:UIControlEventTouchUpInside];
imagev = [[UIImageView alloc]init];
imagev.frame = CGRectMake(10, 250, self.view.frame.size.width-20, 400);
imagev.backgroundColor = [UIColor redColor];
[self.view addSubview:imagev];
}
//同步get方法
//get是完全公开的 网址是暴露的
//拿到网址的图片并显示到uiimageview上
//http://www.sinaimg.cn/dy/slidenews/4_img/2014_50/704_1502763_259801.jpg
//-(void)synchronizeGet
//{
// //获取网址
// NSString *str = @"http://www.sinaimg.cn/dy/slidenews/4_img/2014_50/704_1502763_259801.jpg";
// //将字符串转换成网址
// NSURL *url =[NSURL URLWithString:str];
// //创建请求
// //1参 URL网址
// //2参 缓存方式(弊端:缓存到内存,数据量大的话会很占用内存,正确的应该缓存到本地)
// //3参 请求超时时间
// NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
// //设置请求方式
// // request.HTTPMethod =@"GET";//(这句也可以不写,因为默认就是get)
// //发送请求(同步请求)
// //1参 request请求
// //2参 服务器响应信息
// //3参 错误信息
// NSURLResponse *response = nil;//服务器信息
// NSError *error = nil;//错误信息
// // 程序会停在这里 直到下载结束才会继续执行后面的代码 所有就导致了APP假死现象
// NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];//用NSURLConnection发送,用一个data接收 直到程序结束
// //展示到uiimageview上
// UIImage *image = [UIImage imageWithData:data];
// imagev.image = image;
//}
-(void)synchronizeGet
{
NSString *str = @"http://project.lanou3g.com/teacher/yihuiyun/lanouproject/activitylist.php";
NSURL *url =[NSURL URLWithString:str];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];//data是下载下来豆瓣的信息
//解析
//最外层是大括号 字典
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSArray *array = [dic objectForKey:@"events"];
NSDictionary *dic1 = [array objectAtIndex:0];
NSLog(@"%@",[dic1 objectForKey:@"title"]);
for (NSDictionary *dic1 in array) {
NSLog(@"%@",[dic1 valueForKey:@"content"]);
}
}
//同步post方式请求数据
-(void)synchronizePost
{
//网址
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体 body中的内容是看不见的 是一个nsdata格式的数据 所以说post请求有保密性质 但是现在很多的APP的post请求还是被一些抓包工具抓出来
NSString *bodyStr = @"date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213";//这段放保密信息
//将字符串转化成nsdata
NSData *data = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];//编码方式
//设置body体
request.HTTPBody = data;
//发送请求
NSURLResponse *response = nil;
NSError *error = nil;
NSData *resultData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//将data转换成字符串
NSString *resultStr =[[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding];
NSLog(@"%@",resultStr);
}
//异步代理(不会卡)
-(void)yibuDelegata
{
NSString *str =@"http://www.sinaimg.cn/dy/slidenews/4_img/2014_50/704_1502763_259801.jpg";
NSURL *url =[NSURL URLWithString:str];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
//用代理下载
[NSURLConnection connectionWithRequest:request delegate:self];
//拿图片的URL
// NSData *data = [NSData dataWithContentsOfURL:<#(NSURL *)#>]
}
#pragma -mark 下载的代理方法(4个)
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
//收到服务器的响应(初始化可变data)
self.myData = [NSMutableData data];
}
//收到服务器返回的数据
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.myData appendData:data];
}
//下载结束
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
UIImage *image = [UIImage imageWithData:self.myData];
imagev.image = image;
}
//下载失败,错误会走的方法
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
}
//异步block
-(void)yibuBlock
{
NSString *str = @"http://www.sinaimg.cn/dy/slidenews/4_img/2014_50/704_1502763_259801.jpg";
NSURL *url = [NSURL URLWithString:str];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
//发送异步block请求
//程序走到这一行 发送请求 不会卡住 继续执行下面的代码 当加载结束之后走block里面的代码
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//下载结束之后走这里
//block里面三个参数: 服务器响应信息 下载的data 错误信息
//展示到uiimageview上
UIImage *image = [UIImage imageWithData:data];
imagev.image = image;
}];
}
效果图: