我写了这个最小的例子来说明我的问题:
#include "curl/curl.h"
#include <stdexcept>
#include <string>
#include <iostream>
#include <stdlib.h>
int main(int argc,char* argv[])
{
// All error checking removed for clarity.
// But all calls return CURLE_OK
curl_global_init(CURL_GLOBAL_ALL);
CURL* curl = curl_easy_init();
curl_easy_setopt(curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:14.0) Gecko/20120405 Firefox/14.0a1");
curl_easy_setopt(curl, CURLOPT_URL, argv[1]);
curl_easy_perform(curl);
long result;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &result);
std::cout << "HTTP RESPONCE: " << result << "\n";
}
编译并运行:
> g++ test.cpp -lcurl
> ./a.out thorsanvil.com
<html><head><title>Nothing here</title></head><body><h1>Nothing Here</h1><h2>Go away</h2></body></html>
HTTP RESPONCE: 200
real 0m5.144s
user 0m0.016s
sys 0m0.000s
如您所见,从服务器获得响应需要 5 秒钟。
如果我使用 wget 重复相同的命令,它只需要 0.2 -> 0.5 秒
> time wget thorsanvil.com
--2012-05-28 05:24:17-- http://thorsanvil.com/
Resolving thorsanvil.com (thorsanvil.com)... 67.170.22.105
Connecting to thorsanvil.com (thorsanvil.com)|67.170.22.105|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 104 [text/html]
Saving to: `index.html'
100%[======================================================================================================================>] 104 --.-K/s in 0s
2012-05-28 05:24:18 (589 KB/s) - `index.html.3' saved [104/104]
real 0m0.493s
user 0m0.008s
sys 0m0.000s
但是使用 curl 命令行工具也很慢
> time curl thorsanvil.com
<html><head><title>Nothing here</title></head><body><h1>Nothing Here</h1><h2>Go away</h2></body></html>
real 0m5.240s
user 0m0.004s
sys 0m0.012s
关于为什么我的简单版本没有按预期工作的任何想法?
已编辑
来自评论。libcurl 的版本
> ls -la /usr/lib/x86_64-linux-gnu/libcurl*
-rw-r--r-- 1 root root 748262 Mar 22 16:51 /usr/lib/x86_64-linux-gnu/libcurl.a
lrwxrwxrwx 1 root root 19 Mar 22 16:51 /usr/lib/x86_64-linux-gnu/libcurl-gnutls.so.3 -> libcurl-gnutls.so.4
lrwxrwxrwx 1 root root 23 Mar 22 16:51 /usr/lib/x86_64-linux-gnu/libcurl-gnutls.so.4 -> libcurl-gnutls.so.4.2.0
-rw-r--r-- 1 root root 360488 Mar 22 16:52 /usr/lib/x86_64-linux-gnu/libcurl-gnutls.so.4.2.0
-rw-r--r-- 1 root root 950 Mar 22 16:51 /usr/lib/x86_64-linux-gnu/libcurl.la
lrwxrwxrwx 1 root root 16 Mar 22 16:51 /usr/lib/x86_64-linux-gnu/libcurl.so -> libcurl.so.4.2.0
lrwxrwxrwx 1 root root 12 Mar 22 16:51 /usr/lib/x86_64-linux-gnu/libcurl.so.3 -> libcurl.so.4
lrwxrwxrwx 1 root root 16 Mar 22 16:51 /usr/lib/x86_64-linux-gnu/libcurl.so.4 -> libcurl.so.4.2.0
-rw-r--r-- 1 root root 381512 Mar 22 16:52 /usr/lib/x86_64-linux-gnu/libcurl.so.4.2.0
> curl --version
curl 7.21.7 (x86_64-unknown-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3
Protocols: dict file ftp ftps gopher http https imap imaps ldap pop3 pop3s rtmp rtsp smtp smtps telnet tftp
Features: GSS-Negotiate IDN IPv6 Largefile NTLM SSL libz TLS-SRP