网络请求

新建一个工程

.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 [email protected]"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 [email protected]"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 [email protected]"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;

}];

}

效果图:

时间: 2024-08-05 23:51:53

网络请求的相关文章

ios编程之网络请求

网络请求有GET请求和POST请求,get和post实现的时候可以选择同步或者异步实现.看一个请求是GET还是POST就看网址后面有没有携带请求体. GET与POST 区别 1.get请求 请求的网址全部明文显示 安全性不高 2.get请求 请求的网址 有字符数的限制 大概255个 3.post请求 请求的网址 不光是有一个请求的网址 还可以携带请求体 这个请求体 是以NSData形式存在 安全性较高 4.post请求没有字符数的限制 GET同步和GET异步 同步请求是在请求数据的时候不能做其他

Swift网络请求(Moya篇)

在使用Alamofire进行网络请求的时候,相信大部分的同学都会封装一个抽象的NetworkLayer,如"APIManager" 或者 "NetworkModel"等等.但是位置业务功能增加,会渐渐混合各种请求,不够清晰,而Moya能很好地解决这类问题.Moya在Alamofire基础上进行封装,是一个允许高度自定义的网络层,可以根据具体的需求进行接口的设置.具体的介绍可以参考Moya的官方链接,结构图如下: 接下来就介绍一下Moya的一些常见的用法: (一)根据

微信小程序 网络请求之re.request 和那些坑

微信小程序有四种网络请求类型,下面只详细介绍普通HTTPS请求(wx.request) 普通HTTPS请求(wx.request) 上传文件(wx.uploadFile) 下载文件(wx.downloadFile) WebSocket通信(wx.connectSocket) 首先,先确认是否设置了合法域名,或者在开发环境下不校验合法域名.关于设置合法域名请看→微信小程序 网络请求之设置合法域名   以下是wx.request的详细说明,截图于微信小程序开发文档 在微信index.js 发起一个普

Android网络请求框架AsyncHttpClient实例详解(配合JSON解析调用接口)

最近做项目要求使用到网络,想来想去选择了AsyncHttpClient框架开进行APP开发.在这里把我工作期间遇到的问题以及对AsyncHttpClient的使用经验做出相应总结,希望能对您的学习有所帮助. 首先按照惯例先来简单了解一些AsyncHttpClient网络框架的一些知识. 1.简介 Android中网络请求一般使用Apache HTTP Client或者采用HttpURLConnect,但是直接使用这两个类库需要写大量的代码才能完成网络post和get请求,而使用android-a

Go实战--实现一个自己的网络请求日志httplogger(The way to go)

生命不止,继续go go go~~~ 之前我们简要介绍了go语言中的log package 和 net/http package,那么我们今天就干点实事儿,将二者结合,实现我们自己的日志记录网络请求. 另外,我们还没有跟你介绍time package,但是也可以看懂的. 首先,我默认你了解go语言的组织结构. 导入需要的package 我们需要 log net/http time三个包 package httplogger import ( "log" "net/http&q

Android实际开发之网络请求组件的封装(OkHttp为核心)

趁周末时间撸了两天代码,将OkHttp网络请求框架进行了一次简单封装,对于实际开发非常有用.. 此次封装主要针对我们经常使用的网络请求的步骤进行封装,在已有框架OkHttp的基础上进行实际开发的封装 发送一个网络请求,有以下三个功能模块: 一:request处理 二:OkHttp核心处理 三:callback处理 我们进行网络请求组件的封装也是根据这三大模块进行封装的,下面规划一下这次封装的一个思维导图: 根据以上思维导图,我们第一步,先进行request的封装: 以下是封装的一个CommonR

【Swift】Alamofile网络请求数据更新TableView的坑

写这篇BLOG前,有些话不得不提一下,就仅当发发恼骚吧... 今天下午为了一个Alamofire取得数据而更新TableView的问题,查了一下午的百度(360也是见鬼的一样),竟然没有一个简单明了的回答, 而唯一几个比较接近答案的,说要 self.tableView.reloadData(),也没有贴上代码,说要放在哪个函数内, 都犹抱琵琶半遮面,让初学者自己采坑,于是郁闷了一下午,刚刚回到家,试想想,要不试试英文网,毕竟Swift就是人家老外的, 说不定老外会告诉你,怎么取得数据并绑定Tab

网络请求三方库——OkHttp

我们知道在Android开发中是可以直接使用现成的API进行网络请求的,就是使用 HttpClient 和 HttpURLConnention ,而Android 4.4 之后 HttpClient 已经被废弃,由于此前一直很流行的三方库 android-async-http 是基于 HttpClient 的,所以作者已经放弃了维护 android-async-http 库,我们在项目中也尽量不要使用这个库. OkHttp是Squaur公司开源的一个高性能Http请求库,它的职责同 HttpUR

Volley源码(2):执行网络请求的流程

上一篇(http://blog.csdn.net/szxgg/article/details/51345859)讲述了当我们调用Volley.newRequest()时,Volley内部这个类做了什么,其实Volley这个类就做了一件事情,就是实例化了RequesQueue,这也符合设计模式中的单一职责,其实主要的处理都在其他类中,有三个类最重要,HttpStack/Network/RequestQueue,之后会讲解这些类的关系及作用,那首先还是结合我们使用Volley时的情形来看看源码内部执

iOS进阶(网络请求)

1.网络请求方式 GET:通过网址字符串  网址字符串最多255字节  所有传输给服务器的数据都显示在网址里,直接可见,不安全 POST:通过data  容量很大 数据被转换成二进制数 安全 2.连接方式 同步连接:程序容易出现卡死现象 异步连接:等待数据返回 (有代理和block两种方式)创建请求对象时,采用NSMutableURLRequest对象并设置请求方式和body主体 POSTBlock异步block //创建一个NSURLSession对象 NSURLSession *sessio