iOS 网络编程(HTTP 同步GET请求,同步POST请求,异步GET请求,异步POST请求)

下面首先介绍一下一些基本的概念---同步请求,异步请求,GET请求,POST请求。

1、同步请求从因特网请求数据,一旦发送同步请求,程序将停止用户交互,直至服务器返回数据完成,才可以进行下一步操作。也就是说同步就意味着阻塞线程,在同步请求过程中主线程中不响应其他事件直到同步请求结束。

2、异步请求就不会阻塞主线程,而会建立一个新的线程来操作,用户发出异步请求后,依然可以进行其他操作,程序可以继续运行。也就是说异步不会阻塞主线程对其他事件的响应,所以用户体验大优于同步请求。

异步请求会使用NSURLConnection委托协议NSURLConnectionDelegate,在请求的不同阶段会回调不同的委托对象方法。

3、下面介绍一下GET和POST的区别(来自博客http://www.cnblogs.com/wxf0701/archive/2008/08/17/1269798.html的介绍

  HTTP定义了与服务器交互的不同方法,最基本的方法是 GET  POST.

      HTTP-GET和HTTP-POST是使用HTTP的标准协议动词,用于编码和传送变量名/变量值对参数,并且使用相关的请求语义。每个HTTP-GET和HTTP-POST都由一系列HTTP请求头组成,这些请求头定义了客户端从服务器请求了什么,而响应则是由一系列HTTP应答头和应答数据组成,如果请求成功则返回应答。

      HTTP-GET以使用MIME类型application/x-www-form-urlencoded的urlencoded文本的格式传递参数。Urlencoding是一种字符编码,保证被传送的参数由遵循规范的文本组成,例如一个空格的编码是"%20"。附加参数还能被认为是一个查询字符串。

 与HTTP-GET类似,HTTP-POST参数也是被URL编码的。然而,变量名/变量值不作为URL的一部分被传送,而是放在实际的HTTP请求消息内部被传送。

(1)get是从服务器上获取数据,post是向服务器传送数据。

(1)   在客户端,Get方式在通过URL提交数据,数据URL可以看到;POST方式,数据放置在HTML HEADER提交。

(2) 对于get方式,服务器端用Request.QueryString获取变量的值,对于post方式,服务器端用Request.Form获取提交的数据。

(2)   GET方式提交的数据最多只能有1024字节,而POST则没有此限制。

(3)   安全性问题。正如在(1)中提到,使用 Get 的时候,参数会显示在地址栏上,而 Post 不会。所以,如果这些数据是中文数据而且是非敏感数据,那么使用 get;如果用户输入的数据不是中文字符而且包含敏感数据,那么还是使用 post为好。

简而言之,GET请求,将参数直接写在访问路径上。操作简单,不过容易被外界看到,安全性不高;POST请求,POST请求操作相对复杂,需要将参数和地址分开,不过安全性高,参数放在body里面,不易被捕获。

下面代码分别介绍这四种请求方式。

一、同步GET请求

[cpp]  view plain copy
  1. //第一步,创建URL  
  2.     NSURL *url = [NSURL URLWithString:@"<span style="color: rgb(51, 51, 51); font-family: Menlo; font-size: 13.63636302947998px;">http://api.hudong.com/iphonexml.do?type=focus-c</span>"];  
  3.     //第二步,通过URL创建网络请求  
  4.     NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy  
  5.                                              timeoutInterval:10];  
  6.     //第三步,连接服务器,发送同步请求  
  7.     NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];  
  8.     NSString *str = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding];  
  9.     NSLog(@"data is :%@",str);  

二、同步POST请求

[cpp]  view plain copy
  1. //第一步,创建URL  
  2.     NSURL *url = [NSURL URLWithString:@"http://api.hudong.com/iphonexml.do"];  
  3.     //第二步,创建请求  
  4.     NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];  
  5.     [request setHTTPMethod:@"POST"];//设置请求方式为POST,默认为GET  
  6.     //第三步,连接服务器  
  7.     NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];  
  8.     NSString *str1 = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding];  
  9.     NSLog(@"%@",str1);  

注意到:NSMutableURLRequest  

NSMutableURLRequest is a subclass of NSURLRequest provided to aid developers who may find it more convenient to mutate a single request object for a series of URL load requests instead of creating an immutable NSURLRequest for each load.

三、异步GET请求

[cpp]  view plain copy
  1. //第一步,创建url  
  2.     NSURL *url = [NSURL URLWithString:@"http://api.hudong.com/iphonexml.do?type=focus-c"];  
  3.     //第二步,创建请求  
  4.     NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];  
  5.     //第三步,连接服务器  
  6.     NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];  
实现代理方法:

[cpp]  view plain copy
  1. //接收到服务器回应的时候调用此方法  
  2. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response  
  3. {  
  4.     NSHTTPURLResponse *res = (NSHTTPURLResponse *)response;  
  5.     NSLog(@"%@",[res allHeaderFields]);  
  6.     self.receiveData = [NSMutableData data];  
  7.       
  8. }  
  9. //接收到服务器传输数据的时候调用,此方法根据数据大小执行若干次  
  10. -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data  
  11. {  
  12.     [self.receiveData appendData:data];  
  13. }  
  14. //数据传完之后调用此方法  
  15. -(void)connectionDidFinishLoading:(NSURLConnection *)connection  
  16. {  
  17.     NSString *receiveStr = [[NSString alloc]initWithData:self.receiveData encoding:NSUTF8StringEncoding];  
  18.     NSLog(@"%@",receiveStr);  
  19. }  
  20. //网络请求过程中,出现任何错误(断网,连接超时等)会进入此方法  
  21. -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error  
  22. {  
  23.     NSLog(@"%@",[error localizedDescription]);  
  24. }  
下面简要说明一下代理方法中第一个方法的处理内容:

在didReceiveResponse方法中是 Returns all the HTTP header fields of the receiver.然后输出显示,结果如下:

[cpp]  view plain copy
  1.  {  
  2.     "Cache-Control" = "no-cache";  
  3.     Connection = "Keep-Alive";  
  4.     "Content-Type" = "text/xml; charset=utf-8";  
  5.     Date = "Mon, 15 Apr 2013 12:37:54 GMT";  
  6.     Expires = "Thu, 01 Jan 1970 00:00:00 GMT";  
  7.     Pragma = "no-cache";  
  8.     "Proxy-Connection" = "Keep-Alive";  
  9.     Server = "nginx/0.7.61";  
  10.     "Set-Cookie" = "JSESSIONID=947667669; domain=.baike.com; path=/, NSC_wt_bqj_ofx-hi=8efb37a6294c;expires=Mon, 15-Apr-13 11:31:28 GMT;path=/";  
  11.     "Transfer-Encoding" = Identity;  
  12.     Via = "1.1 WORKISA";  
  13. }  
四、 异步POST请求

[cpp]  view plain copy
  1. //第一步,创建url  
  2.     NSURL *url = [NSURL URLWithString:@"http://api.hudong.com/iphonexml.do"];  
  3.     //第二步,创建请求  
  4.     NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];  
  5.     [request setHTTPMethod:@"POST"];//设置请求方式为POST,默认为GET  
  6.     //第三步,连接服务器  
  7.     NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];  

代理方法实现如上异步GET请求。

部分代码转自:http://blog.csdn.net/crayondeng/article/details/8800960

对于https,自己测试使用的是下面的方法:

事件触发 

    NSString *urlString =[NSString stringWithFormat:@"https://127.0.0.1/default.aspx?USER=%@",@"111"];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]        cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:5];

    //设置请求方式为get

    [request setHTTPMethod:@"GET"];

    //添加用户会话id

    [request addValue:@"text/html" forHTTPHeaderField:@"Content-Type"];

    //连接发送请求

    finished = false;

    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

//堵塞线程,等待结束

while(!finished) {

[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];

}

 

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

{

UserData = [NSMutableData new];

}

 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 

{

 NSError *error;

    NSDictionary *userInfoDic = [NSJSONSerialization JSONObjectWithData:self.m_userData

                                                               options:NSJSONReadingMutableContainers

                                                                 error:&error];

    //[_waitingDialog dismissWithClickedButtonIndex:0 animated:NO];

}

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

}

- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection{

    return NO;

}

//下面两段是重点,要服务器端单项HTTPS 验证,iOS 客户端忽略证书验证。

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {

    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {    

    NSLog(@"didReceiveAuthenticationChallenge %@ %zd", [[challenge protectionSpace] authenticationMethod], (ssize_t) [challenge previousFailureCount]);

    

    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]){

        [[challenge sender]  useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];

        [[challenge sender]  continueWithoutCredentialForAuthenticationChallenge: challenge];

    }

    NSLog(@"get the whole response");

    //[receivedData setLength:0];

}

//处理数据 

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

[Userdata appendData data];

}  


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值