查找URL的下载大小(Content-Length)

时间:2012-03-20 00:34:08

标签: iphone objective-c ios

我正在寻找一些Objective-c代码来查询网址并提供下载大小,类似于此示例:Checking Download size before download

但是在objective-c中,使用ASIHttp就可以了。

3 个答案:

答案 0 :(得分:6)

启动HTTP HEAD请求:

NSURL *url = [NSURL URLWithString:@"http://www.google.com/"];
NSMutableURLRequest *httpRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
[httpRequest setHTTPMethod:@"HEAD"];
NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest:httpRequest delegate:self];

实施委托:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)aResponse {
   long long filesize = [aResponse expectedContentLength];
}

答案 1 :(得分:0)

答案是一样的。 HTTP HEAD请求。在你引用的帖子中没有特定于语言的内容。

答案 2 :(得分:0)

自iOS 9以来的新功能,应使用NSURLSession代替不推荐使用的NSURLConnection

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:@"http://www.google.com/"
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:10];
[request setHTTPMethod:@"HEAD"];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config
                                                      delegate:nil
                                                 delegateQueue:queue];
[[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
  {
      NSLog(@"%lld", response.expectedContentLength);
  }] resume];