NSURLConnection详解

来源:http://blog.csdn.net/paulluo0739/article/details/6843312

URLRequest 的一个实例:(获取北京的天气情况)

- (void)weather {
	NSURL *url = [NSURL URLWithString:@"http://www.weather.com.cn/adat/cityinfo/101010100.html"];
	NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:10.0];
	NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        //可以用代理方式实现<span>        
        //NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];<pre name="code" class="cpp">	NSDictionary *weatherDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
	NSDictionary *weatherInfo = [weatherDict objectForKey:@"weatherinfo"];
	
	NSString *city = [weatherInfo objectForKey:@"city"];
	NSString *weather = [weatherInfo objectForKey:@"weather"];
	
	NSLog(@"city:%@ weather:%@",city,weather);
}
 
 

其中:
NSURLRequest默认的cache policy是 NSURLRequestUseProtocolCachePolicy,是最能保持一致性的协议。
NSURLRequestReloadIgnoringCacheData 忽略缓存直接从原始地址下载
NSURLRequestReturnCacheDataElseLoad 只有在cache中不存在data时才从原始地址下载
NSURLRequestReturnCacheDataDontLoad 允许app确定是否要返回cache数据,如果使用这种协议当本地不存在response的时候,创建NSURLConnection or NSURLDownload实例时将会马上返回nil;这类似于离线模式,没有建立网络连接;

你只需要实现以下delegate方法来处理数据响应

- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSHTTPURLResponse*)response
- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error
- (void)connectionDidFinishLoading:(NSURLConnection *)connection

NSURLConnect还提供了一个方便的类方法(class method) : sendSynchronousRequest:returningResponse:error:可用来 同步地加载一个URL请求

+ (NSData *)sendSynchronousRequest:    (NSURLRequest *)request      returningResponse:   (NSURLResponse **)response    error:  (NSError **)error

  • request 要装载的URL请求. 这个request 对象 作为初始化进程的一部分,被深度复制(deep-copied). 在这个方法返回之后, 再修改request, 将不会影响用在装载的过程中的request
  • reponse 输出参数, 由服务器返回的URL响应
  • error   输出参数, 如果在处理请求的过程中发生错误,就会使用.  无错误,就为NULL
一个实现异步get请求的例子:

- (void)setURLRequest_connection {
    NSString *url = [NSString stringWithFormat:@"http://localhost/chat/messages.php?past=%ld&t=%ld",lastId, time(0)];  
      
    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];  
    [request setURL:[NSURL URLWithString:url]];  
    [request setHTTPMethod:@"GET"];  
  
    NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request delegate:self];    
    if (conn)  
    {    
        receivedData = [[NSMutableData data] retain];    
    }     
}
  
- (void)timerCallback {  
    //[timer release];  
    [self getNewMessages];  
}  
  
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response    
{    
    [receivedData setLength:0];    
}    
  
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data    
{    
    [receivedData appendData:data];    
}    
  
- (void)connectionDidFinishLoading:(NSURLConnection *)connection    
{    
    if (chatParser)  
        [chatParser release];  
      
    if ( messages == nil )  
        messages = [[NSMutableArray alloc] init];  
  
    chatParser = [[NSXMLParser alloc] initWithData:receivedData];  
    [chatParser setDelegate:self];//set the delegate  
    [chatParser parse];//start parse  
  
    [receivedData release];    
      
    [messageList reloadData];  
      
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector: @selector(timerCallback)]];  
    [invocation setTarget:self];  
    [invocation setSelector:@selector(timerCallback)];  
    //timer = [NSTimer scheduledTimerWithTimeInterval:5.0 invocation:invocation repeats:NO];  
    [NSTimer scheduledTimerWithTimeInterval:5.0 invocation:invocation repeats:NO];//if set yes,then very 5 seconds updata the table  
}

一个实现同步Get请求的例子:

    // 初始化请求  
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];           
    // 设置URL  
    [request setURL:[NSURL URLWithString:urlStr]];  
    // 设置HTTP方法  
    [request setHTTPMethod:@"GET"];  
    // 发 送同步请求, 这里得returnData就是返回得数据了  
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];   
    // 释放对象  
    [request release];  

更多详细信息请参见苹果开发文档:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值