网络请求
2016-05-17 本文已影响90人
简简简简简书
网络请求
http和https
URL
- URL的基本格式 = 协议://主机地址/路径
- 协议:不同的协议代表不同的资源查找方式和资源的传输方式
- 主机地址:存放资源的主机的IP地址(域名)
- 路径:资源在主机中的位置
C/S模式
- client和server在相距很远的计算机上
- client是将用户的要求提交给server,再将server返回的结果展示给用户
- server是将接受用户程序提出的服务请求,进行相应的处理,再讲结果返还给用户
HTTPS
- 安全超文本传输协议,在HTTP基础上使用SSL进行信息交换
- SSL:是运行在TCP和IP层之上,应用层之下的,为应用程序提供加密数据通道
- https协议需要到CA申请证书,一般需要收费
- http和https使用完全不同的连接方式,所以端口也不一样,前者80,后者443
- http的链接简单,是无状态的,传输完一次数据就立刻断开
get和post
- get是通过网址字符串传输数据,post是通过data
- get允许网址字符串最多255字节,post使用NSdata,容量超过1G(实际允许不超过4G)
- get的所有传输给服务的数据,都会显示在网址里,直接可见的,而post的数据被转成NSData,无法直接读取,所以较为安全
实现网络编程
- 若网址字符串URLString中有汉字,需要用一下方式转码
str = [str stringByAddingPercentEscapesUsingEncoding:[ NSCharacterSet URLQueryAllowedCharacterSet]];
NSURLConnection(ios9之后已经弃用了)
get请求
- 发送同步的get请求并解析数据
//定义的宏,一种是get用到的url,一种是post用到的url
#define KURL @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20151101&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"
#define PURL @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"
//发送同步的get请求
NSURL *url =[NSURL URLWithString:KURL];
// NSLog(@"%@,%@",url.scheme,url.host);
// 1.url 2.httpcache的方式 3.超时时间
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
// 发送请求
NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
if (data) {
id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@",json);
//response是响应(包含响应头和响应体)
NSLog(@"%@",response);
}
- 发送异步的get请求(block方式)并解析数据
//异步get
NSURL *url = [NSURL URLWithString:KURL];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 1.request 2. 主队列 3. 返回结果的block
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@",json);
}];
NSLog(@"先走这里");
- 发送异步的get请求(代理方式)并解析数据
//代理异步get(事先引入代理NSURLConnectionDataDelegate)
- (void)delegateGet
{
NSURL *url = [NSURL URLWithString:KURL];
// 创建请求
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 连接
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
// 开始请求
[connection start];
//
// [connection cancel]; //取消
}
//服务器接收到请求,开始响应,准备返回数据
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
}
//接收数据(如果data比较大,会走很多次,需要拼接)
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// 把请求到的数据data拼接
[self.data appendData:data];
}
//请求数据结束
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
id json = [NSJSONSerialization JSONObjectWithData:self.data options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@",json);
}
//失败
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
}
post
- 发送异步的post请求(block)并解析数据
#pragma mark 异步post
//异步post
- (void)post
{
//POST
NSURL *url = [NSURL URLWithString:PURL];
NSMutableURLRequest *requset = [NSMutableURLRequest requestWithURL:url];
// 设置请求方式(post请求方式和参数必须设置)
requset.HTTPMethod =@"POST";
// 设置请求参数
NSString *str =@"date=20151101&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
requset.HTTPBody = data;
// 设置请求头
// requset setValue:<#(nullable NSString *)#> forHTTPHeaderField:<#(nonnull NSString *)#>
[NSURLConnection sendAsynchronousRequest:requset queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@",json);
}];
}
- 发送异步的post请求(代理)并解析数据
//代理异步post(代理方法与get是一样的,并且实现原理是相同的)
- (void)delegatePost
{
NSURL *url = [NSURL URLWithString:PURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
NSString *str = @"date=20151101&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = data;
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
[connection start];
}
NSURLSession
get
- 发送异步的get请求(block)并解析数据
- (void)blockGet
{
//sessionGet
//初始化session
NSURLSession *session = [NSURLSession sharedSession];
// get请求
NSURLSessionDataTask *task =[session dataTaskWithURL:[NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20151101&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@",json);
}];
//开启任务(默认挂起,需要手动开启)
[task resume];
}
- 发送异步的get请求(代理)并解析数据
- (void)delegateGet
{
// 控制任务的相关属性(事先引入代理NSURLSessionDataDelegate)
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
//初始化session
//1.任务的控制面板 2.代理 3.代理回调的线程(一般是主线程)
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue mainQueue]];
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20151101&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"]];
[dataTask resume];
}
//接收请求头
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(nonnull NSURLResponse *)response completionHandler:(nonnull void (^)(NSURLSessionResponseDisposition))completionHandler
{
//允许处理服务器的响应,才会继续接受服务器返回的数据
completionHandler(NSURLSessionResponseAllow);
}
//接收数据
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
[self.data appendData:data];
}
//结束接收数据或者出错
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
if (!error) {
id json = [NSJSONSerialization JSONObjectWithData:self.data options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@",json);
}
}
- 发送异步的post请求(block)并解析数据
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"]];
//设置请求方法
request.HTTPMethod = @"POST";
request.HTTPBody = [@"date=20151101&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213" dataUsingEncoding:NSUTF8StringEncoding];
//初始化
NSURLSession *session = [NSURLSession sharedSession];
//创建任务
NSURLSessionDataTask *datatask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//解析数据
id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@",json);
}];
// 开启
[datatask resume];