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

iOS开发4-NSURLConnection实现Http通信

2015-10-20 20:13 573 查看
1.Http协议

HTTP协议(HyperText Transfer Protocol,超文本传输协议)是用于从WWW服务器传输超文本到本地浏览器的传送协议。
HTTP协议在TCP/IP的应用层。

物理层(第一层)
数据链路层
网络层
传输层
会话层
表示层

应用层(第7层)(HTTP)
HTTP是一个应用层协议,由请求和响应构成,是一个标准的客户端服务器模型。
HTTP协议永远都是客户端发起请求,服务器回送响应。这样就限制了使用HTTP协议,无法实现在客户端没有发起请求的时候,服务器将消息推送给客户端。
HTTP协议是一个无状态的协议,同一个客户端的这次请求和上次请求是没有对应关系。
默认HTTP的端口号为80,HTTPS的端口号为443。

工作流程
一次HTTP操作称为一个事务,其工作过程可分为四步:
1)首先客户机与服务器需要建立连接。只要单击某个超级链接,HTTP的工作开始。
2)建立连接后,客户机发送一个请求给服务器,请求方式的格式为:统一资源标识符(URL)、协议版本号,后边是MIME信息包括请求修饰符、客户机信息和可能的内容。
3)服务器接到请求后,给予相应的响应信息,其格式为一个状态行,包括信息的协议版本号、一个成功或错误的代码,后边是MIME信息包括服务器信息、实体信息和可能的内容。
4)客户端接收服务器所返回的信息通过浏览器显示在用户的显示屏上,然后客户机与服务器断开连接。

如果在以上过程中的某一步出现错误,那么产生错误的信息将返回到客户端,有显示屏输出。
对于用户来说,这些过程是由HTTP自己完成的,用户只要用鼠标点击,等待信息显示就可以了。

2.[b]NSURLConnection实现Http通信[/b]
2.1 GET方式
2.1.1 GET同步
NSLog(@"get同步");
//get同步【不推荐使用】【阻塞主线程】
//URL
NSURL *url=[NSURL URLWithString:@"http://localhost/?userName=yan30&password=123"];
//创建请求对象  默认是get请求
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
//创建响应对象
NSURLResponse * response=nil;
//错误
NSError *error=nil;
//建立连接,传输数据
NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//打印响应
NSLog(@"response=%@",response);

//解析时候,data为空,就会崩溃
if (data!=nil)
{
NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@",dic);

}
else NSLog(@"解析失败");

/*执行结果
2015-10-20 20:10:50.099 NSURLConnection1-1020homework[7444:351532] get同步
2015-10-20 20:10:50.142 NSURLConnection1-1020homework[7444:351532] response=<NSHTTPURLResponse: 0x7fc51a57e100> { URL: http://localhost/?userName=yan30&password=123 } { status code: 200, headers {
Connection = "Keep-Alive";
"Content-Length" = 33;
"Content-Type" = "text/html";
Date = "Tue, 20 Oct 2015 12:10:50 GMT";
"Keep-Alive" = "timeout=5, max=100";
Server = "Apache/2.4.10 (Unix) OpenSSL/1.0.1i PHP/5.5.15 mod_perl/2.0.8-dev Perl/v5.16.3";
"X-Powered-By" = "PHP/5.5.15";
} }
2015-10-20 20:10:50.142 NSURLConnection1-1020homework[7444:351532] {
code = ready;
test = welcome;
}
*/


2.1.2 GET异步(Block)
NSLog(@"get异步");
//get异步
//URL
NSURL *url=[NSURL URLWithString:@"http://localhost/?userName=yan30&password=123"];
//创建请求对象  默认是get请求
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
//创建响应对象
NSURLResponse * response=nil;
//错误
NSError *error=nil;
//建立连接,传输数据
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {

if (data!=nil)
{
self.dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(@"get异步--self.dict=%@",self.dict);

}
else NSLog(@"解析失败");

}];
//打印响应
NSLog(@"get异步--response=%@",response);

NSLog(@"get异步--self.dict=%@",self.dict);//这里打印不出-异步执行,此时不一定解析完毕
/*运行结果

2015-10-20 20:35:05.099 NSURLConnection1-1020homework[7484:366960] get异步
2015-10-20 20:35:05.104 NSURLConnection1-1020homework[7484:366960] get异步--response=(null)
2015-10-20 20:35:05.104 NSURLConnection1-1020homework[7484:366960] get异步--self.dict=(null)
2015-10-20 20:35:05.140 NSURLConnection1-1020homework[7484:366960] get异步--self.dict={
code = ready;
test = welcome;
}

*/

2.2 POST方式
2.2.1POST同步
NSLog(@"post同步");
//post同步【不推荐使用】
//URL
NSURL *url=[NSURL URLWithString:@"http://localhost/"];//和get不同
//创建请求对象
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
//设置成POSt请求
[request setHTTPMethod:@"POST"];
//参数
NSString *s=@"userName=yan30&password=123";
//将字符串转成NSData类型
NSData *param=[s dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:param];
//创建响应对象
NSURLResponse * response=nil;
//错误
NSError *error=nil;
//建立连接,传输数据
NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

//打印响应
NSLog(@"response=%@",response);
//解析
//解析时候,data为空,就会崩溃
if (data!=nil)
{
NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@",dic);

}
else NSLog(@"解析失败");

/* 运行结果
2015-10-20 20:37:36.399 NSURLConnection1-1020homework[7498:369150] post同步
2015-10-20 20:37:36.427 NSURLConnection1-1020homework[7498:369150] response=<NSHTTPURLResponse: 0x7ff242cd4630> { URL: http://localhost/ } { status code: 200, headers {
Connection = "Keep-Alive";
"Content-Length" = 33;
"Content-Type" = "text/html";
Date = "Tue, 20 Oct 2015 12:37:36 GMT";
"Keep-Alive" = "timeout=5, max=100";
Server = "Apache/2.4.10 (Unix) OpenSSL/1.0.1i PHP/5.5.15 mod_perl/2.0.8-dev Perl/v5.16.3";
"X-Powered-By" = "PHP/5.5.15";
} }
2015-10-20 20:37:36.428 NSURLConnection1-1020homework[7498:369150] {
code = ready;
test = welcome;
}

*/


2.2.2POST异步(代理)
NSLog(@"post异步-代理");
//URL
NSURL *url=[NSURL URLWithString:@"http://localhost"];
//创建请求对象
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
//设置成POST请求
[request setHTTPMethod:@"POST"];
//参数
NSString *s=@"userName=yan30&password=123";
//将字符串转成NSData类型
NSData *param=[s dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:param];
//创建响应对象
NSURLResponse * response=nil;
//错误
NSError *error=nil;
//建立连接,传输数据
NSURLConnection *conn=[[NSURLConnection alloc]initWithRequest:request delegate:self];
[conn start];

/*
2015-10-20 20:40:19.676 NSURLConnection1-1020homework[7512:371264] post异步-代理
2015-10-20 20:40:19.717 NSURLConnection1-1020homework[7512:371264] post异步代理
2015-10-20 20:40:19.717 NSURLConnection1-1020homework[7512:371264] post异步代理:{
code = ready;
test = welcome;
}

*/


遵守代理协议

#import "ViewController.h"
@interface ViewController ()<NSURLConnectionDataDelegate>
@property(nonatomic,strong)NSDictionary *dict;
@property(nonatomic,strong)NSMutableData *appendData;//拼接收到的数据
@end
@implementation ViewController


实现代理方法

//post代理
#pragma mark NSURLConnection协议方法
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
//接收响应
NSLog(@"post异步代理");
self.appendData=[NSMutableData data];//初始化
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
//接收数据
//如果数据很大的话,数据是分批送到的
//拼接数据
[self.appendData appendData:data];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
//完成接收数据,开始解析
//解析
NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:self.appendData options:NSJSONReadingAllowFragments error:nil];
NSLog(@"post异步代理:%@",dic);

}


由于iOS9弃用NSURLConnection方法,如果要使用NSURLConnection,要设置一下info.plist文件。



代码下载(Xcode7.0.1)

有问题请联系博主,邮箱:nathanlee1987@aliyun.com
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: