且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在C ++中使用Curl获取HTTP响应字符串

更新时间:2023-02-24 14:30:54

您的代码看起来没有多大错.我根据您的代码运行了以下代码,以阅读BBC新闻网站的首页:

There doesn't look to be much wrong with your code. I ran the following code, based on yours, to read the front page of the BBC news website:

#include <iostream>
#include <string>
#include <curl/curl.h>

size_t WriteCallback(char *contents, size_t size, size_t nmemb, void *userp)
{
    ((std::string*)userp)->append((char*)contents, size * nmemb);
    return size * nmemb;
}

int main(int argc, char * argv[])
{
    curl_global_init(CURL_GLOBAL_ALL);

    CURL* easyhandle = curl_easy_init();
    std::string readBuffer;

    curl_easy_setopt(easyhandle, CURLOPT_URL, "http://www.bbc.co.uk/news");
    curl_easy_setopt(easyhandle, CURLOPT_VERBOSE, 1L);
    curl_easy_setopt(easyhandle, CURLOPT_PROXY, "http://my.proxy.net");   // replace with your actual proxy
    curl_easy_setopt(easyhandle, CURLOPT_PROXYPORT, 8080L);
    curl_easy_setopt(easyhandle, CURLOPT_WRITEFUNCTION, WriteCallback);
    curl_easy_setopt(easyhandle, CURLOPT_WRITEDATA, &readBuffer);

    curl_easy_perform(easyhandle);

    std::cout << readBuffer << std::endl;

    return 0;
}

...,我得到了完整的HTML响应.注意:我必须使用代理,并且启用了详细模式才能查看正在发生的情况.也NB;HTTP服务器可能会对您提供的URL感到困惑:如果我替换 http://www.bbc.co.uk/news http://www.bbc.co.uk/news/(即带有斜杠的末尾),那么我没有返回任何数据(响应长度为零),如冗长的curl输出所指出的那样:

... and I got the full HTML response. NB I had to use a proxy, and I enabled verbose mode to see what was happening. Also NB; the HTTP server might be fussy about the URL you give it: if I replace http://www.bbc.co.uk/news with http://www.bbc.co.uk/news/ (i.e. with a trailing slash) then I get no data back (a response length of zero), as noted by the verbose curl output:

Host: www.bbc.co.uk
Accept: */*
Proxy-Connection: Keep-Alive

< HTTP/1.1 301 Moved Permanently
< X-Cache-Action: PASS (no-cache-control)
< Vary: Accept-Encoding
< X-Cache-Age: 0
< Content-Type: text/html;charset=utf-8
< Date: Mon, 10 Jul 2017 16:42:20 GMT
< Location: http://www.bbc.co.uk/news
< X-XSS-Protection: 1; mode=block
< X-Content-Type-Options: nosniff
< X-Frame-Options: SAMEORIGIN
< Content-Length: 0
< X-Cache: MISS from barracuda1.[my proxy].net
< Connection: keep-alive
< 
* Connection #0 to host [my proxy] left intact

此处,Content-Length为0,并且从未调用过WriteCallback()函数.希望这可以帮助.

Here, Content-Length is 0 and the WriteCallback() function is never called. Hope this helps.