//同步方法发送请求并获取返回数据
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]);
}
NSURLConnection
最新推荐文章于 2019-02-16 22:40:00 发布