命令行获取,如果获取百度首页返回的信息大小,返回如下信息
curl –head www.baidu.com
$ curl –head www.baidu.com
HTTP/1.1 200 OK
Server: bfe/1.0.8.18
Date: Sat, 16 Sep 2017 07:31:35 GMT
Content-Type: text/html
Content-Length: 277
Last-Modified: Mon, 13 Jun 2016 02:50:26 GMT
Connection: Keep-Alive
ETag: “575e1f72-115”
Cache-Control: private, no-cache, no-store, proxy-revalidate, no-transform
Pragma: no-cache
Accept-Ranges: bytes
代码实现这里写链接内容
我封装了一下
#include <curl/curl.h>
size_t get_size_struct(void* ptr, size_t size, size_t nmemb, void* data){
return (size_t)(size * nmemb);
}
double get_download_size(char* url){
CURL* curl;
CURLcode res;
double size = 0.0;
curl = curl_easy_init();
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_NOBODY, 1L);
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, get_size_struct);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
res = curl_easy_perform(curl);
res = curl_easy_getinfo(curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &size);
if(res != CURLE_OK){
fprintf(stderr, "curl_easy_getinfo() failed: %s\n", curl_easy_strerror(res));
}
curl_easy_cleanup(curl);
return size;
}
int getfilesize(char *url){
double filesize = get_download_size(url);
printf("[%0.0lf] %s\n", filesize, url);
return filesize;
}
@implementation RacURLFile
-(RACSignal*) requsetURLFileSize:(NSString *)urlStr{
RACSignal *signal;
signal = [RACSignal createSignal: ^RACDisposable *(id<RACSubscriber> subscriber) {
dispatch_async(dispatch_get_global_queue(0, 0),^(void){
long size;
size = (long)getfilesize([urlStr cStringUsingEncoding:NSUTF8StringEncoding]);
[subscriber sendNext:[NSNumber numberWithInt:size]];
[subscriber sendCompleted];
});
return nil;
}];
return signal;
}
@end
ios实现 取文件大小, 注意,经测试,如下的方法会下载整个文件不推荐,建议使用libcurl的方法
-(RACSignal*) requsetURLFileSize:(NSString *)urlStr{
RACSignal *signal;
signal = [RACSignal createSignal: ^RACDisposable *(id<RACSubscriber> subscriber) {
dispatch_async(dispatch_get_global_queue(0, 0),^(void){
NSURL *url = [NSURL URLWithString:urlStr];
NSURLRequest *request = [NSURLRequest requestWithURL: url];
NSHTTPURLResponse *response;
[NSURLConnection sendSynchronousRequest: request returningResponse: &response error: nil];
if ([response respondsToSelector:@selector(allHeaderFields)]) {
// 取得所有的请求的头
NSDictionary *dictionary = [response allHeaderFields];
NSLog([dictionary description]);
// 取得http状态码
NSLog(@"%d, %ld",[response statusCode], [response expectedContentLength]);
if([response statusCode] == 200){
[subscriber sendNext:[NSNumber numberWithInt: [response expectedContentLength]]];
[subscriber sendCompleted];
}
}});
return nil;
}];
return signal;
}