您的位置:首页 > 理论基础 > 计算机网络

iOS网络数据请求

2016-05-06 21:52 459 查看

HTTP和HTTPS协议

URL全称是Uniform ResourceLocator(统一字典定位符)通过一个URL,能够找到互联网上唯一的11个资源

URL就是资源的地址,位置,互联网上的每个资源都有一个唯一URL

URL的基本格式 = 协议://主机地址/路径()如http://www.lanou3g.com/szzr/

协议:不同的协议代表着不同国的资源查找方式,资源传输方式

主机地址:存放资源的主机的IP地址(域名)

路径:资源在主机中的位置

HTTP协议:Hyper Text Transfer Protocol(超文本传输协议)是用于从万维网(www)服务器传送超文本到本地浏览器的传输协议,HTTP是一个应用层协议,由请求和响应构成,是一个标准的客户端服务器模型,客户端向服务器发送一个请求报文,服务器以一个状态作为响应.

C/S模式:Client和Server常常分别处在相距很远的两台计算机上,Client程序任务是将用户的要求提交给Server程序,再将server程序返回的结果以特定的形式显示给用户;Server程序的任务是接收客户程序提出的服务请求,进行相应的处理,再将结果返回给客户程序.

HTTPS(Secure Hyper Text Transfer Protocol)安全超文本传输协议,它是一个安全通道.基于HTTP开发,用于在客户计算机和服务器之间的交换信息,它使用安全套接字层(SSL)进行信息交换,简单来说它是HTTP的安全版.HTTPS协议使用SSL在发送和接受方通过交换共和的密匙来实现,因此,所传送的数据不容易被网络黑客截获和解密.

SSL是Netscape公司所提出安全保密协议,运行在TCP/IP层之上,应用层之下,为应用层提供加密数据通道

HTTP和HTTPS的异同:

https协议需要到cd申请证书,一般免费证书很少,需要交费.

http是超文本传输协议,信息是明文传输,https则是具有安全性的ssl加密传输协议

http和https使用的是完全不同的链接方式,用的端口也不一样,前者是80,后者是443

http的链接很简单,是无状态的

https是协议是由SSL+HTTP协议构建的可进行加密传输,身份认证的网络协议,要比http安全.

HTTP协议的常见的请求方式:GET和POST

相同点:都能给服务器传输数据.

不同点:

给服务器传输数据的方式不同:

GET:通过网址字符串.

POST:通过data.

传输数据的大小:

GET:网址字符串最多255.

使用NSData,容量超过1G.

安全性:

GET:所有传输给服务的数据,显示的网址里,类似于密码的明文输入,直接可见.

POST:数据被转成NSData(二进制数据),类似于密码的密文输入,无法直接读取.

HTTP协议请求如何实现

NSURL

url:统一资源定位符,也被称为网址,因特网上标准的资源网址

一个典型url: http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20151031&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213

url的符语法:协议://授权/路径?查询

协议:
ftp://(文件传输协议)http://(超文本传输协议) https://(安全超文本传输协议)file://(本地文件协议)
连接方式:

同步连接:程序容易出现卡死现象

异步连接:等待数据返回

异步连接有两种实现方式:

设置代理,接收数据

实现block

同步请求

GetSynchronization get同步请求

- (void)getAndSynchronization {
//1 创建网址对象
NSString *urlString = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20151031&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
NSURL *url = [NSURL URLWithString:urlString];
//2 创建请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//3 发送请求,连接服务器(这个方法虽然能过时了但是能使用)
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//4 解析
if (data) {
self.getDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
//        NSLog(@"%@",self.getDic);
if(self.getDic){
//判断对象是否支持json格式
if ([NSJSONSerialization isValidJSONObject:self.getDic]) {
//将字典转换为json串
NSData *strData = [NSJSONSerialization dataWithJSONObject:self.getDic options:NSJSONWritingPrettyPrinted error:nil];
if (strData) {
//将data转换为字符串
NSString *str = [[NSString alloc] initWithData:strData encoding:NSUTF8StringEncoding];
NSLog(@"%@",str);
}
}
}
} else {
NSLog(@"请求失败");
}
}


post同步请求

- (void)postAndSynchronization {
//第一步:创建URL
NSURL *url = [NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"];
//第二步:创建请求
NSString *postStr = @"date=20151031&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
NSData *postData = [postStr dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
//设置请求方式为POST,默认为GET
request.HTTPMethod = @"POST";
//设置body
request.HTTPBody = postData;
//第三方:连接服务器
NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
dic = [NSJSONSerialization JSONObjectWithData:received options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@",dic);
}


异步请求

异步block请求

- (void)getAndAsychronousBlock {
//网址
NSURL *url = [NSURL URLWithString:@"http://mapi.weibo.com/2/remind/unread_count?remind_version=199&networktype=wifi&with_comment_attitude=1&ext_all=0&moduleID=700&c=android&i=ed0d41d&s=f32076c0&ua=Xiaomi-MI%203__weibo__6.4.0__android__android4.4.4&wm=20005_0002&aid=01AtCI_i9CnkwZ8amfinkM-ZJWFOpF0gsEw_rwX43XUPpDgT8.&idc=&v_f=2&from=1064095010&gsid=_2A256CymIDeTxGeNG6FQQ9i_NwjqIHXVWgTpArDV6PUJbrdAKLXjFkWoNYAQ8b7QA8jEG-5JLCblfTetI5w..&lang=zh_CN&skin=default&oldwm=9975_0028&sflag=1&with_settings=1&unread_message=1&with_page_group=1"];
//请求
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//异步连接block方式
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];

NSLog(@"%@",dic);

NSLog(@"请求到数据了");
}];
NSLog(@"我在block的地下");
}


post 异步协议代理方式

- (void)postAndDelegate {
//网址
/*
date=20151031&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213
*/
NSURL *url = [NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"];
//post请求对象构建
NSMutableURLRequest *mutableURLRequest = [NSMutableURLRequest requestWithURL:url];
//设置请求方式
[mutableURLRequest setHTTPMethod:@"POST"];
//设置参数
//需要将参数转换为data类型
NSString *str = @"date=20151031&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
[mutableURLRequest setHTTPBody:data];
//请求超时
[mutableURLRequest setTimeoutInterval:60];
//需要设置代理,所以我们需要一个连接对象
NSURLConnection *connection = [NSURLConnection connectionWithRequest:mutableURLRequest delegate:self];
}


#pragma mark - NSURLConnectionDelegate,NSURLConnectionDataDelegate协议方法
//服务器开始响应,准备返回数据
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
//初始化receiveData,用来接收数据
self.receiveData = [[NSMutableData alloc] init];
NSLog(@"开始返回响应");
}
//客户端接收数据
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
//返回的数据不是一次返回而是分批返回,所以我们需要一个可变的data类型来接收它
NSLog(@"开始接收数据");
[self.receiveData appendData:data];
}
//数据请求完毕
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"数据已经返回完毕");
NSMutableDictionary *dict = [NSJSONSerialization JSONObjectWithData:self.receiveData options:NSJSONReadingAllowFragments error:nil];
if (dict) {
if ([NSJSONSerialization isValidJSONObject:dict]) {
NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",str);
}
}
}

//网络请求失败
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"请求出错----%@",error);
}


iOS7之后请求变化

NSURLSession get请求(block)

- (void)sessionAndGet {
//网址
NSURL *url = [NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20151031&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"];
//建立加载数据任务
NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@",dic);
}];
//启动任务
[dataTask resume];
}


NSURLSession post请求block

- (void)sessionAndPost {
//网址
NSURL *url = [NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"];
//设置NSMutableURLRequest
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//设置请求方式
request.HTTPMethod = @"POST";
//设置参数
request.HTTPBody = [@"date=20151031&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213 " dataUsingEncoding:NSUTF8StringEncoding];
//创建一个session对象,用来进行post请求
NSURLSession *session = [NSURLSession sharedSession];
//建立任务
NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//解析
NSMutableDictionary *mDict = [NSMutableDictionary dictionary];
mDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@",mDict);
}];
//启动任务
[task resume];
}
#pragma mark - NSURLSessionDataDelegate,,NSURLSessionDelegate协议方法
//NSURLSessionDataDelegate代理方法
//NSURLSession提供了block方式处理返回数据的简单方式,但如果想要在接收数据过程中做进一步的处理,仍然可以调用相关的协议方法,NSURLSession的代理方法和NSURLConnection有些类似,都是分为接收响应,接收数据,请求完成几个阶段
//使用代理方法我们需要设置代理,但是session的delegate属性是只读的,要想设置代理只能通过这种方式创建session
- (void)sessionAndDelegate {
//网址
NSURL *url = [NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"];
//创建一个session对象,用来进行请求
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
//创建任务(因为要使用代理方法,就不需要block方式初始化)
//    NSURLSessionDataTask *task = [session dataTaskWithURL:url];//这个方法只能用在get请求中
NSURLSessionDataTask *task = [session dataTaskWithRequest:[NSURLRequest requestWithURL:url]];
//启动任务
[task resume];
}

//代理方法
//接收服务器响应
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
//允许处理服务器的响应,才会继续接收服务器返回的数据
completionHandler(NSURLSessionResponseAllow);
//当网络请求基于http协议时(url以http开头),response本质为NSHTTPURLResponse类型
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
//创建空的可变的data,准备接收服务器传回的data片段
self.recervedData = [NSMutableData dataWithCapacity:40];
}
//接收服务器数据(可能多次,手动拼接数据)
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
//处理每次收到的数据
//将每次接收到的data片段,拼接到receivedData中
[self.recervedData appendData:data];
}
//请求结果(失败后error对象被赋值错误信息)
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
//请求完成,成功或者失败的处理
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
dic = [NSJSONSerialization JSONObjectWithData:self.recervedData options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@",dic);
}


下载

- (void)downLoadTask {
//创建网址
NSURL *url = [NSURL URLWithString:@"http://mapi.weibo.com/2/remind/unread_count?remind_version=199&networktype=wifi&with_comment_attitude=1&ext_all=0&moduleID=700&c=android&i=ed0d41d&s=f32076c0&ua=Xiaomi-MI%203__weibo__6.4.0__android__android4.4.4&wm=20005_0002&aid=01AtCI_i9CnkwZ8amfinkM-ZJWFOpF0gsEw_rwX43XUPpDgT8.&idc=&v_f=2&from=1064095010&gsid=_2A256CymIDeTxGeNG6FQQ9i_NwjqIHXVWgTpArDV6PUJbrdAKLXjFkWoNYAQ8b7QA8jEG-5JLCblfTetI5w..&lang=zh_CN&skin=default&oldwm=9975_0028&sflag=1&with_settings=1&unread_message=1&with_page_group=1"];
//创建session对象
NSURLSession *session = [NSURLSession sharedSession];
//创建下载的任务模式(会话模式)
NSURLSessionDownloadTask *downLoadTask = [session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error) {
NSLog(@"error:%@",error.description);
} else {
//下载好的文件存储的路径是在一个临时文件中/Users/xalo/Desktop/
//创建一个需要保存下载文件的路径
NSURL *targetURL = [NSURL fileURLWithPath:@"/Users/xalo/Desktop/herJSON.json"];
//将临时路径下的文件拷贝到桌面文件
NSFileManager *manager = [NSFileManager defaultManager];
//copy
[manager copyItemAtURL:location toURL:targetURL error:nil];
//move
//            [manager moveItemAtURL:location toURL:targetURL error:nil];
NSLog(@"location:%@",location);

}
}];
//启动任务
[downLoadTask resume];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: