c++ - libcurl获取html源码失败
迷茫
迷茫 2017-04-17 11:13:48
0
1
593

这是最简单的获取html源码的代码:

#include <stdio.h>
#include <curl/curl.h>

int main(void)
{
  CURL *curl;
  CURLcode res;

  curl = curl_easy_init();
  if(curl) {
    curl_easy_setopt(curl, CURLOPT_URL, "http://www.cnblogs.com");
    /* example.com is redirected, so we tell libcurl to follow redirection */ 
    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);

    /* Perform the request, res will get the return code */ 
    res = curl_easy_perform(curl);
    /* Check for errors */ 
    if(res != CURLE_OK)
      fprintf(stderr, "curl_easy_perform() failed: %s\n",
              curl_easy_strerror(res));

    /* always cleanup */ 
    curl_easy_cleanup(curl);
  }
  return 0;
}

但是,如果我加上http请求头之后,发现没法获取源码了,请朋友帮忙指点下,谢谢啦!

        //http请求头
        struct curl_slist *headers = NULL;
        headers = curl_slist_append(headers,"Host: www.cnblogs.com");
        headers = curl_slist_append(headers,"User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0");
        headers = curl_slist_append(headers,"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        headers = curl_slist_append(headers,"Accept-Language: zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
        headers = curl_slist_append(headers,"Accept-Encoding: gzip, deflate");
        headers = curl_slist_append(headers,"Connection: keep-alive");
        headers = curl_slist_append(headers,"If-Modified-Since: Mon, 09 Dec 2013 03:41:17 GMT");

        curl_easy_setopt(easy_handle, CURLOPT_HTTPHEADER, headers);
迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

Antworte allen(1)
左手右手慢动作

去掉以下一行代码就可以了:

headers = curl_slist_append(headers,"Accept-Encoding: gzip, deflate");
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage