【问题标题】:finding the download size of a URL (Content-Length)查找 URL 的下载大小(内容长度)
【发布时间】:2012-03-20 00:34:08
【问题描述】:

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

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

【问题讨论】:

标签: iphone objective-c ios


【解决方案1】:

发起 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];
}

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      自 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];
      

      【讨论】:

        猜你喜欢
        • 2015-02-18
        • 2013-08-09
        • 1970-01-01
        • 2023-03-10
        • 1970-01-01
        • 1970-01-01
        • 2017-12-27
        • 1970-01-01
        • 2011-07-16
        相关资源
        最近更新 更多