标签:
注:文中出现的网站只做用例子,所以有些已经失效的网站,具体URL大家可以自己上网搜索相关资源。
一、HTTP和HTTPS协议
1、URL:
2、HTTP协议的概念:HTTP协议,Hyper Text Transfer Protocol(超文本传输协议)是用于从万维网(WWW)服务器传送超文本到本地浏览器的传输协议,HTTP是一个应用层协议,由请求和响应构成,是一个标准的客户端服务器模型。
3、HTTP的工作原理:HTTP 协议采用请求/响应模型。客户端向服务器发送一个请求报文,服务器以一个状态作为响应。
4、了解C/S模式:Client和Server常常分别处在相距很远的两台计算机上,Client程序的任务是将用户的要求提交给Server程序,再将Server程序返回的结果以特定的形式显示给用户;Server程序的任务是接收客户程序提出的服务请求,进行相应的处理,再将结果返回给客户程序。
5、Https:HTTPS(Secure Hypertext Transfer Protocol)安全超文本传输协议 它是一个安全通信通道,它基于HTTP开发,用于在客户计算机和服务器之间交换信息。 它使用安全套接字层(SSL)进行信息交换,简单来说它是HTTP的安全版。 HTTPS协议使用SSL在发送方把原始数据进行加密,然后在接收方进行解密,加密和解密需要发送方和接受方通过交换共知的密钥来实现,因此,所传送的数据不容易被网络黑客截获和解密。
6、SSL:SSL是Netscape公司所提出的安全保密协议,在浏览器(如Internet Explorer、Netscape Navigator)和Web服务器(如Netscape的Netscape Enterprise Server、ColdFusion Server等等)之间构造安全通道来进行数据传输,SSL运行在TCP/IP层之上、应用层之下,为应用程序提供加密数据通道。
7、HTTP和HTTPS的异同:
二、HTTP协议的常见请求方式
1、请求方式:GET、POST。
2、两种请求方式比较:
三、iOS实现网络编程
1、HTTP协议请求如何实现:
2、NSURL:
3、连接方式:
4、同步连接:GET同步,POST同步。
5、注意:使用http请求,首先需要打开网络适配:在工程info文件中添加下列代码即可
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
6、同步连接代码:(iOS7之前,下述方法部分已弃用)
#define GET_URL @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213" #define POST_URL @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx" #define POST_BODY @"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"
// 1.创建URL NSURL *url = [NSURL URLWithString:GET_URL]; // 2.根据url创建具体的请求(使用缓存策略) // 参数1:统一资源定位符 url // 参数2:缓存策略 (枚举值) /* //NSURLRequestUseProtocolCachePolicy//(基础策略) //NSURLRequestReloadIgnoringLocalCacheData//(忽略本地缓存) //NSURLRequestReturnCacheDataElseLoad//(首先使用缓存,如果没有本地缓存,才从原地址下载) //NSURLRequestReturnCacheDataDontLoad//(使用本地缓存,从不下载,如果本地没有缓存,则请求失败,此策略多用于离线操作) www.2cto.com //NSURLRequestReloadIgnoringLocalAndRemoteCacheData//(无视任何缓存策略,无论是本地的还是远程的,总是从原地址重新下载) //NSURLRequestReloadRevalidatingCacheData//(如果本地缓存是有效的则不下载,其他任何情况都从原地址重新下载) NSURLRequestReloadIgnoringCacheData = NSURLRequestReloadIgnoringLocalCacheData,优先使用本地缓存,如果没有从网络加载(不论有效无效) */ // 参数3:设置延迟时间,如果超时请求终止 NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20]; // 3.连接服务器 [NSURLConnection在iOS9之后已经被启用] // 参数1:请求对象 // 参数2:存储一些网络请求的信息(一般为包体)一般为nil // 参数3:错误信息 NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; // 4.进行json数据解析 NSDictionary *resultDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(@"dic = %@",dic);
// 1.创建URL(post网站打开是不全的) NSURL *url = [NSURL URLWithString:POST_URL]; // 2.根据url创建网络请求(post请求必须初始化为可变请求,因为稍后要进行一些内容的设置) NSMutableURLRequest *mRequest = [NSMutableURLRequest requestWithURL:url]; // 设置body // 创建一个连接字符串(这个内容在以后的开发中接口文档都有标注) NSString *dataString = POST_BODY; // 对连接字符串进行编码 NSData *postData = [dataString dataUsingEncoding:NSUTF8StringEncoding]; // 设置请求格式为POST请求(必须大写) [mRequest setHTTPMethod:@"POST"]; // 设置请求体(body) [mRequest setHTTPBody:postData]; // 3.连接服务器 NSData *data = [NSURLConnection sendSynchronousRequest:mRequest returningResponse:nil error:nil]; // 4.进行json数据解析 NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; NSLog(@"dic = %@",dic);
7、异步连接代码:
// 1.创建URL NSURL *url = [NSURL URLWithString:GET_URL]; // 2.创建网络请求 NSURLRequest *request = [NSURLRequest requestWithURL:url]; [NSURLConnection connectionWithRequest:request delegate:self];
#pragma mark - NSRULConnectionDataDelegate相关的代理方法 // 服务器开始响应 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { self.resultData = [NSMutableData data]; } // 开始接收数据 // 这个方法会重复执行,得到的每段数据拼接在一起就可以了 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [self.resultData appendData:data]; } // 结束服务器 - (void)connectionDidFinishLoading:(NSURLConnection *)connection { // 进行数据解析 NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:self.resultData options:NSJSONReadingAllowFragments error:nil]; NSLog(@"%@", dict); }
// 1.创建url NSURL *url = [NSURL URLWithString:POST_URL]; // 2.获取网络请求 NSMutableURLRequest *mRequest = [NSMutableURLRequest requestWithURL:url]; // 设置连接字符串 NSString *dataString = POST_BODY; // 转换格式 NSData *postData = [dataString dataUsingEncoding:NSUTF8StringEncoding]; // 设置请求类型 [mRequest setHTTPMethod:@"POST"]; // 设置请求体 [mRequest setHTTPBody:postData]; // 3.连接服务器 [NSURLConnection sendAsynchronousRequest:mRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) { // 解析数据 NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; NSLog(@"%@",dict); }];
四、iOS7之后请求变化
1、NSURLSession:
2、GET请求(Block)
// 方式一:使用block实现 // 创建url NSURL *url = [NSURL URLWithString:GET_URL]; // 创建NSURLSession对象 NSURLSession *session = [NSURLSession sharedSession]; // 创建task请求任务,通过URL初始化task,在block内部可以直接对返回的数据进行处理 // NSURLSession是基于任务去完成相关的事件的 // NSURLSessionTask所有的任务均放在这个里边实现 // 对数据进行加载:使用NSURLSessionDataTask和NSURLSessionTask两者没有本质区别 // 要处理下载任务的时候使用此任务:NSURLSessionDownloadTask // 要处理上传任务使用:NSURLSessionUploadTask NSURLSessionTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { // 解析数据 NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; NSLog(@"%@", dict); }]; // 启动任务(NSURLSessionTask实例出来的任务处于挂起状态,如果不启动,不会走block中的实现内容) [task resume];
3、GET请求(协议Delegate)
NSURL *url = [NSURL URLWithString:GET_URL]; // 创建session // 参数1:模式的设置(默认会话模式(default),瞬时会话模式(ephemeral),后台会话模式(background)) // 参数2:代理 // 参数3:主线程队列 NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]]; // 创建task任务 NSURLSessionDataTask *task = [session dataTaskWithURL:url]; [task resume]; #pragma mark - NSURLSessionDataDelegate协议的实现方法 // 接受服务器响应 - (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,稍后进行片段的拼接存储 self.resultData = [NSMutableData data]; } // 接受数据拼接 - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data { // 反复执行,然后拼接相关的片段 [_resultData appendData:data]; } // 数据接受完成,网络请求结束 - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { // 解析 if (error == nil) { NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:self.resultData options:NSJSONReadingAllowFragments error:nil]; NSLog(@"%@", dic); } }
4、POST请求(Block)
// 创建url NSURL *url = [NSURL URLWithString:POST_URL]; // 创建请求 NSMutableURLRequest *mRequest = [NSMutableURLRequest requestWithURL:url]; [mRequest setHTTPMethod:@"POST"]; [mRequest setHTTPBody:[POST_BODY dataUsingEncoding:NSUTF8StringEncoding]]; // 通过request初始化task NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:mRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; NSLog(@"%@", dict); }]; [task resume];
5、POST请求(协议Delegate)
NSURL *url = [NSURL URLWithString:POST_URL]; // 创建session // 参数1:模式的设置(默认会话模式(default),瞬时会话模式(ephemeral),后台会话模式(background)) // 参数2:代理 // 参数3:主线程队列 NSMutableURLRequest *mRequest = [NSMutableURLRequest requestWithURL:url]; [mRequest setHTTPMethod:@"POST"]; [mRequest setHTTPBody:[POST_BODY dataUsingEncoding:NSUTF8StringEncoding]]; NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]]; // 创建task任务 NSURLSessionDataTask *task = [session dataTaskWithRequest:mRequest]; [task resume]; // 协议部分与GET相同
6、NSURLSession数据任务:适合于小的数据访问,例如:JSON、XML、Plist、HTML、图像。
标签:
原文地址:http://www.cnblogs.com/soley/p/5483673.html