使用NSURLConnection创建http连接

iOS应用程序连接WEB服务器操作过程,使用的是http协议。cocoa中有现成的类如NSURLConnection,用来建立http连接。也有开源的包如ASIHTTPRequest也提供很好的实现http连接的方法。我使用NSURLConnection类做一个测试,实现http的连接操作。
http(超文本传输协议)是一个基于请求与响应模式的、无状态的、应用层的协议,常基于TCP的连接方式,HTTP1.1版本中给出一种持续连接的机制,绝大多数的Web开发,都是构建在HTTP协议之上的Web应用。
浏览器请求WEB连接时,输入请求字符串是:http://host[":"port][abs_path],称之为URL。
这里,关键字"http"表示要通过HTTP协议来定位网络资源;"host"表示合法的Internet主机域名或者IP地址;"port"指定一个端口号,为空则使用缺省端口80;"abs_path"指定请求资源的URI;如果URL中没有给出abs_path,那么当它作为请求URI时,必须以“/”的形式给出,通常这个工作浏览器自动帮我们完成。

HTTP协议永远都是客户端发起请求,服务器回送响应。服务器端不会去主动连接客户端,也不能去连接客户端,这就是HTTP协议的限制。HTTP协议无法实现,在客户端没有发起请求的时候服务器端将消息推送给客户端的操作。 所以说,HTTP协议是一个无状态的协议,同一个客户端的这一次请求和上一次请求是没有对应关系。在客户端发起请求,服务器回送响应之后,服务器端会新建一个session或根据客户端发送过来的请求包中的信息是否使用已有的session,这样HTTP连接就建立起来了。

有一个图形很形象,可以很好地描述这种操作,如下:


关于http连接和操作还有很多细节,有些我知道,有些我不知道,这里不深入,以后再写。现在我使用NSURLConnection来实现http连接操作。

NSURLConnection建立连接有异步和同步两种。异步就是不堵塞应用的其他操作;同步就是堵塞住所有操作,等它结束。

我在XCode4.5上,创建一个简单的单视图应用,使用ARC机制。

在视图控制器类WebViewController的头文件上新建一个NSMutableData类型的变量receivedData,保存http连接返回的响应报文信息,并遵守协议NSURLConnectionDelegate,后者是为了异步操作。
//
//  WebViewController.h
//  WebTT
//
//  Created by mikewang on 13-2-1.
//  Copyright (c) 2013年 mikixiyou. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface WebViewController : UIViewController <NSURLConnectionDelegate>
{
    NSMutableData * receivedData;
}
@end

在视图控制器类WebViewController的实现文件中,在viewDidLoad方法增加http连接操作的代码,并实现NSURLConnectionDelegate的一些委托方法。

//
//  WebViewController.m
//  WebTT
//
//  Created by mikewang on 13-2-1.
//  Copyright (c) 2013年 mikixiyou. All rights reserved.
//

#import "WebViewController.h"

@implementation WebViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    // 创建一个可操作的request对象
    NSMutableURLRequest *theRequest = [[NSMutableURLRequest alloc] init];
    
    NSString *url = [NSString stringWithFormat:@"http://blog.csdn.net/mikixiyou"];
    
    [theRequest setURL:[NSURL URLWithString:url]];
    [theRequest setHTTPMethod:@"GET"];
    
    NSLog(@"request header is %@",[[theRequest allHTTPHeaderFields] description]);
    
    // create the connection with the request
    // and start loading the data
    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    if (theConnection) {
        // Create the NSMutableData to hold the received data.
        // receivedData is an instance variable declared elsewhere.
        receivedData = [NSMutableData data];        
        
    } else {
        // Inform the  user that the connection failed.
        NSLog(@"http://blog.csdn.net/mikixiyou");
    }
    
    
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    //把请求到的数据存放可变数组字典 - 切字别在这里处理数据,因为这不代表数据完全下载完.我在此磨了一个星期得出的结论.别走我的路.
    [receivedData appendData:data];
}

#pragma mark NetworkController Delegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"Received response: %@", response);
    NSHTTPURLResponse *httpResponse=(NSHTTPURLResponse *)response;
    NSLog(@"Received response allHeaderFields: %@",[[httpResponse allHeaderFields] description]);
}

#pragma mark NetworkController Delegate
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
   
     NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);
    
    NSString * receivedString= [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
    
    NSLog(@"%@",receivedString);
    
 
}

#pragma mark NetworkController Delegate
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"Error receiving response: %@", error);
    //[connection release];
}



@end

这样,就是实现一个最最基础的http连接操作。至于如何修改request的信息,如何使用post方法,如何保存cookie,如何管理web缓存,如何使用https连接等等,还需要另外分析。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值