NSURLConnection

13 篇文章 0 订阅
11 篇文章 0 订阅
    //同步方法发送请求并获取返回数据
    NSURLResponse *response = [[NSURLResponse alloc]init];
    NSData *data = [NSURLConnection    sendSynchronousRequest:request returningResponse:&response error:nil];
    NSLog(@"%@",[(NSHTTPURLResponse *)response allHeaderFields]);
    
    NSLog(@"%d", [(NSHTTPURLResponse *)response statusCode]);
    常用方法:
    //异步方法发送请求下载
    NSURLConnection *_asyncConnect = nil;
    if(_asyncConnect == nil) {
    	NSURL *asyncURL = [NSURL URLWithString:@"http:// mirrors.163.com/ubuntu-releases/13.04/ubuntu-13.04- desktop-amd64.iso"];
        NSURLRequest *asyncRequest = [NSURLRequest requestWithURL:asyncURL];
        _asyncConnect = [[NSURLConnection alloc]initWithRequest:asyncRequest delegate:self];}
    //开始请求
    [_asyncConnect start]; 

集中常用的协议方法:

//请求连接出错的处理方法
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@“%@: failed:%@", [[connection currentRequest] URL], error);
}
//请求连接返回的响应头的处理方法!
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"response status code:%d",[(NSHTTPURLResponse *)response statusCode]);
NSLog(@"response expect length:%lld", [(NSHTTPURLResponse *)response expectedContentLength]);
NSLog(@"response all headfield:%@",[(NSHTTPURLResponse *)response allHeaderFields]);
}
//请求连接收到数据的处理方法,数据量大就可能会不断调用
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSString *dataStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",dataStr);
}
//请求连接处理完成收据收发后的处理方法
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSSLog(@"connent to %@ finished", [[connection currentRequest] URL]);
} 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值