本文转载至 http://blog.csdn.net/zaitianaoxiang/article/details/6650469
- (void)loadView {
NSURLConnection *hc=nil;
@try{ NSURL *url=[NSURL URLWithString:@http://218.206.70.212/SingleDemo/file/480/soumoneyhaidaotuan_1_10001000.dmh];
NSMutableURLRequest* request=[NSMutableURLRequest requestWithURL:url];
[request setValue:@"bytes=200 - 1200" forHTTPHeaderField:@"Range"];
//清空缓存(如果不加这一行,重复调用的时候总显示第一次的数据)
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
//这个是同步网络的调用方法
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//nsdata转换成char 打印读出来的数据
char* bu=[returnData bytes];
for (int i=0; i<[returnData length];i++){
NSLog(@"打印数据:%d",bu[i]);
//异步调用方法
//hc=[NSURLConnection sendSynchronousRequest:request returningResponse:nil err:nil];
//[hc start];
if (hc) {
网络连接好了
}
}
以下方法全是异步时所调用的方法
- (void)connection:(NSURLConnection*)connection didReceiveResponse:
(NSHTTPURLResponse*)response {
//response saved so that status Codes can be checked later
_response = [response retain];
NSDictionary* headers = [response allHeaderFields];
int contentLength = [[headers objectForKey:@"Content-Length"] intValue];
//append the responseData used in connectionDidFinishLoading:
_responseData = [[NSMutableData alloc] initWithCapacity:contentLength];
}
//获取数据
- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data {
[_responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *error {NSLog(@"Connection failed: %@", [error description]);}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[hc release];
}