现在的移动开发必然涉及到服务器,那就不能不说网络。在网络编程中,有几个基本的概念:

  • 客户端(Client): 移动应用 (iOS, Android等应用)
  • 服务器(Server): 为客户端提供服务、提供数据、提供资源的机器
  • 请求(Request): 客户端向服务器索取数据的一种行为
  • 响应(Response): 服务器对客户端的请求作出响应,一般指返回数据给客户端

图解:

客户端是如何找到服务器呢,主要是通过URL找到想要连接的服务器,而什么是URL?

  • URL的全称是 Uniform Resource Locator (统一起源定位符)
  • 通过1个URL,能找到互联网上唯一的一个资源
  • URL就是资源的地址,位置,互联网上的每一个资源都有唯一的URL
  • URL的基本格式 = 协议://主机地址/路径(http://www.baidu.com/img/logo.png)

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

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

路径: 资源在主机(服务器)中的具体位置

HTTP协议的特点:

  • 简单快速

因为http协议简单,所以Http服务器的程序规模小,因而通信速度很快

  • 灵活

Http允许各种各样的数据

Http协议规定: 一个完整的由客户端和服务器端的Http请求包括以下内容:

iOS中发送Http的请求方案:

  • 苹果原生:NSURLConnection(比较古老,不推荐使用), NSURLSession(推荐使用)
  • 第三方框架: AFNetworking


NSURLConnection的GET

  1. 常用类
  • NSURL:请求地址
  • NSURLRequest:一个NSURLRequest对象就代表一个请求,它包含的信息有(一个NSURL对象, 请求方法、请求头、请求体,请求超时......)
  • NSMutableURLRequest:NSURLRequest的子类
  • NSURLConnection (负责发送请求,建立客户端和服务器的连接发送数据给服务器,并收集来自服务器的响应数据)

2.   NSURLConnection的使用步骤

  • 创建一个NSURL对象,设置请求路径
  • 传入NSURL创建一个NSURLRequest对象,设置请求头和请求体
  • 使用NSURLConnection发送请求

3. 发送同步请求: 主要使用+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error;方法

 /*GET:http://120.25.226.186:32812/login?username=123&pwd=456&type=JSON协议+主机地址+接口名称+?+参数1&参数2&参数3post:http://120.25.226.186:32812/login协议+主机地址+接口名称*///GET,没有请求体//1.确定请求路径NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it&type=JSON"];//2.创建请求对象//请求头不需要设置(默认的请求头)//请求方法--->默认为GETNSURLRequest *request = [[NSURLRequest alloc]initWithURL:url];//3.发送请求//真实类型:NSHTTPURLResponseNSHTTPURLResponse *response = nil;/*第一个参数:请求对象第二个参数:响应头信息第三个参数:错误信息返回值:响应体*///该方法是阻塞的,即如果该方法没有执行完则后面的代码将得不到执行NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];//4.解析 data--->字符串//NSUTF8StringEncodingNSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);NSLog(@"%zd",response.statusCode);

4. 发送异步请求: 主要使用两类方法

  • Block方法

+ (void)sendAsynchronousRequest:(NSURLRequest*) request  queue:(NSOperationQueue*) queue                                                  completionHandler:(void (^)(NSURLResponse* response, NSData* data, NSError* connectionError)) handler;

//1.确定请求路径NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it&type=JSON"];//2.创建请求对象//请求头不需要设置(默认的请求头)NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url];//3.发送异步请求/*第一个参数:请求对象第二个参数:队列 决定代码块completionHandler的调用线程第三个参数:completionHandler 当请求完成(成功|失败)的时候回调response:响应头data:响应体connectionError:错误信息*/[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {//4.解析数据NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);NSHTTPURLResponse *res = (NSHTTPURLResponse *)response;NSLog(@"%zd",res.statusCode);NSLog(@"%@",[NSThread currentThread]);}];
  • 代理方法
- (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate;
+ (NSURLConnection*)connectionWithRequest:(NSURLRequest *)request delegate:(id)delegate;
- (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate startImmediately:(BOOL)startImmediately;在startImmediately = NO的情况下,需要调用start方法开始发送请- (void)start;

成为NSURLConnection的代理,最好遵守NSURLConnectionDataDelegate协议

5. NSURLConnectionDataDelegate协议中的代理方法

  • 开始接收到服务器的响应时调用

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;

  • 接收到服务器返回的数据时调用(服务器返回的数据比较大时会调用多次)

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;

  • 服务器返回的数据完全接收完毕后调用

- (void)connectionDidFinishLoading:(NSURLConnection *)connection;

  • 请求出错时调用(比如请求超时)

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;

-(void)delegate
{//1.确定请求路径NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=123&pwd=123&type=JSON"];//2.创建请求对象NSURLRequest *request = [NSURLRequest requestWithURL:url];//3.设置代理,发送请求//3.1//[NSURLConnection connectionWithRequest:request delegate:self];//3.2//[[NSURLConnection alloc]initWithRequest:request delegate:self];//3.3 设置代理,时候发送请求需要检查startImmediately的值//(startImmediately == YES 会发送 | startImmediately == NO 则需要调用start方法)NSURLConnection * connect = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:NO];//调用开始方法[connect start];//    [connect cancel];//取消
}#pragma mark ----------------------
#pragma mark NSURLConnectionDataDelegate
//1.当接收到服务器响应的时候调用
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{NSLog(@"%s",__func__);
}//2.接收到服务器返回数据的时候调用,调用多次
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{NSLog(@"%s",__func__);//拼接数据[self.resultData appendData:data];
}
//3.当请求失败的时候调用
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{NSLog(@"%s",__func__);
}//4.请求结束的时候调用
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{NSLog(@"%s",__func__);NSLog(@"%@",[[NSString alloc]initWithData:self.resultData encoding:NSUTF8StringEncoding]);
}

NSURLConnection的POST

1. 常用类与GET类似

2. 比较特殊的处理方法

NSMutableURLRequest是NSURLRequest的子类,常用方法有

  • 设置请求超时等待时间(超过这个时间就算超时,请求失败)

- (void)setTimeoutInterval:(NSTimeInterval)seconds;

  • 设置请求方法(比如GET和POST)

- (void)setHTTPMethod:(NSString *)method;

  • 设置请求体

- (void)setHTTPBody:(NSData *)data;

  • 设置请求头

- (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field;

-(void)post
{//1.确定请求路径NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login"];//2.创建可变请求对象NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];//3.修改请求方法,POST必须大写request.HTTPMethod = @"POST";//设置属性,请求超时(超过这个时间算请求失败)request.timeoutInterval = 10;//设置请求头User-Agent//注意:key一定要一致(用于传递数据给后台)[request setValue:@"ios 10.1" forHTTPHeaderField:@"User-Agent"];//4.设置请求体信息,字符串--->NSDatarequest.HTTPBody = [@"username=520it&pwd=123&type=JSON" dataUsingEncoding:NSUTF8StringEncoding];//5.发送请求[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {//6.解析数据,NSData --->NSStringNSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);}];
}

代理方法与上面block类似,除了添加request.HTTPMethod和request.HTTPBody等其余与GET的代理一样。


NSURLConnection小文件下载


#import "ViewController.h"@interface ViewController ()<NSURLConnectionDataDelegate>
/** 注释 */
@property (nonatomic, strong) NSMutableData *fileData;
@property (nonatomic, assign) NSInteger totalSize;
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@end@implementation ViewController-(NSMutableData *)fileData
{if (_fileData == nil) {_fileData = [NSMutableData data];}return _fileData;
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{[self download3];
}//耗时操作[NSData dataWithContentsOfURL:url]
-(void)download1
{//1.urlNSURL *url = [NSURL URLWithString:@"http://img5.imgtn.bdimg.com/it/u=1915764121,2488815998&fm=21&gp=0.jpg"];//2.下载二进制数据NSData *data = [NSData dataWithContentsOfURL:url];//3.转换UIImage *image = [UIImage imageWithData:data];
}//1.无法监听进度
//2.内存飙升
-(void)download2
{//1.url// NSURL *url = [NSURL URLWithString:@"http://imgsrc.baidu.com/forum/w%3D580/sign=54a8cc6f728b4710ce2ffdc4f3cec3b2/d143ad4bd11373f06c0b5bd1a40f4bfbfbed0443.jpg"];NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"];//2.创建请求对象NSURLRequest *request = [NSURLRequest requestWithURL:url];//3.发送请求[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {//4.转换
//        UIImage *image = [UIImage imageWithData:data];
//
//        self.imageView.image = image;//NSLog(@"%@",connectionError);//4.写数据到沙盒中NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]stringByAppendingPathComponent:@"123.mp4"];[data writeToFile:fullPath atomically:YES];}];
}//内存飙升
-(void)download3
{//1.url// NSURL *url = [NSURL URLWithString:@"http://imgsrc.baidu.com/forum/w%3D580/sign=54a8cc6f728b4710ce2ffdc4f3cec3b2/d143ad4bd11373f06c0b5bd1a40f4bfbfbed0443.jpg"];NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"];//2.创建请求对象NSURLRequest *request = [NSURLRequest requestWithURL:url];//3.发送请求[[NSURLConnection alloc]initWithRequest:request delegate:self];
}#pragma mark ----------------------
#pragma mark NSURLConnectionDataDelegate
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{NSLog(@"didReceiveResponse");//得到文件的总大小(本次请求的文件数据的总大小)self.totalSize = response.expectedContentLength;
}-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{// NSLog(@"%zd",data.length);[self.fileData appendData:data];//进度=已经下载/文件的总大小NSLog(@"%f",1.0 * self.fileData.length /self.totalSize);
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
}-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{NSLog(@"connectionDidFinishLoading");//4.写数据到沙盒中NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]stringByAppendingPathComponent:@"123.mp4"];[self.fileData writeToFile:fullPath atomically:YES];NSLog(@"%@",fullPath);
}
@end

iOS网络(一): Http协议通信及NSURLConnection的GET和POST方法,小文件下载相关推荐

  1. 如何网络监测其他计算机关闭445端口,关闭445端口的方法,小编告诉你电脑如何关闭445端口-站长资讯中心...

    摘要:相信大家都听说过勒索病毒吧,通过445端口传播,它是一个名称为"wannacry"的新家族,该木马通过加密形式,锁定用户电脑里的txt.doc.ppt.xls等后缀名类型的文 ...

  2. iOS开发网络篇—HTTP协议

    说明:apache tomcat服务器必须占用8080端口 一.URL 1.基本介绍 URL的全称是Uniform Resource Locator(统一资源定位符) 通过1个URL,能找到互联网上唯 ...

  3. iOS网络编程开发—HTTP协议

    iOS网络编程开发-HTTP协议 说明:apache tomcat服务器必须占用8080端口 一.URL 1.基本介绍 URL的全称是Uniform Resource Locator(统一资源定位符) ...

  4. 02.iOS开发网络篇—HTTP协议

    iOS开发网络篇-HTTP协议 说明:apache tomcat服务器必须占用8080端口 一.URL 1.基本介绍 URL的全称是Uniform Resource Locator(统一资源定位符) ...

  5. ios开发网络篇—HTTP协议 - 转

    一.URL 1.基本介绍  URL的全称是Uniform Resource Locator(统一资源定位符) ,通过1个URL,能找到互联网唯一的1个资源 ,URL就是资源的地址,位置,互联网上的每个 ...

  6. IOS —— 网络那些事(上) - http协议

    作为一名并不太合格的程序员,今天要分享学习的成果,竟然讲的是网络相关HTTP协议的事情.(也算是复习了) 乍看HTTP协议的内容着实是十分复杂的,涉及到十分多互联网"底层"框架的东 ...

  7. 【QT网络编程】实现UDP协议通信

    文章目录 概要:本期主要讲解QT中对UDP协议通信的实现. 一.UDP协议通信 二.Qt中UDP协议的处理 1.QUdpSocket 三.Qt实现UDP通信 1.客户端 2.服务器端 结尾 概要:本期 ...

  8. Linux_网络_数据链路层协议 MAC帧/ARP协议 (以太网通信原理,MAC地址与IP地址的区分,MTU对IP/TCP/IP的影响,ARP协议及其通信过程)

    文章目录 1. 以太网(基于碰撞区与碰撞检测的局域网通信标准) 2. 以太网的帧格式(MAC帧) MAC地址,IP地址的区分 MTU MTU对IP协议的影响 MTU对TCP/UDP协议的影响 3.AR ...

  9. ipv6协议与网络服务器有关,IPv6与IPv4协议网络中的双工通信差异

    我们都知道IPv6与IPv4协议网络的本质区别.那么在进行双向会话通信过程中两者有什么差异呢?下面我们就来详细说一下这方面的内容.Ipv6和IPv4协议动态NAT一样,NAT-PT只能用于由IPv6网 ...

最新文章

  1. 送你一份概率图模型笔记
  2. 【深度学习入门到精通系列】特别正经的合理调参介绍~❤️
  3. python做小程序-抖音最火的整蛊表白小程序如何做出来的?教你用python做出
  4. 零基础可以学python吗-Python编程语言好学吗?零基础转行能学Python吗?
  5. 一篇文章 学会 iOS中的 代理(delegate) 设计模式
  6. ASP.NET-Session cooike
  7. 【ARM】ARM处理器寻址方式
  8. joomla添加html,如何将自定义html代码添加到Joomla 2.5菜单项?
  9. 什么是商业模式(概念篇)
  10. 【Excel 教程系列第 1 篇】删除所有空白行,隐藏空白行
  11. 路由器下一跳地址怎么判断_Tracert命令详解,路由跟踪命令tracert命令怎么用?...
  12. springboot 热插拔JRebel
  13. HttpsUtil(GET/POST/DELETE/PUT)
  14. Agile敏捷开发管理Salesforce项目(第一篇)- 4大核心价值观+12条原则
  15. SQL查询 — 自连接的用法
  16. 统计建模与R软件(绪论)
  17. 模仿天猫实战【SSM版】——后台开发
  18. 家装灯线走线图_家装电路布线施工图文并茂详细解说
  19. 光伏自动化出图系统 基于C#的AutoCad二次开发
  20. PHP 时间计算(距离现在多长时间)

热门文章

  1. 51nod1326 遥远的旅途(spfa+dp)
  2. coreldraw凹槽_CATIA课时:操作工具栏创建修剪分割曲面视频教程_翼狐网
  3. ImageLoader 修改个人头像
  4. 【案例 4-2】饲养员喂养动物
  5. 2.1安装前的准备工作---安装Red Hat Linux
  6. 大型欧姆龙PLC NJ系列ST语言Ethercat总线24轴 伺服电池生产线欧姆龙PLC程序大型程序NJ系列
  7. 相机光学(十五)——如何提高相机标定的精度
  8. 计算机网络技术2020,计算机网络技术超星2020试题及答案
  9. JVM基础知识---对象的创建过程
  10. 聊聊WEB项目中的图片