recherche

Maison  >  Questions et réponses  >  le corps du texte

c++ - libcurl获取html源码失败

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

<code>#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;

}

</code>

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

1

2

3

4

5

6

7

8

9

10

11

12

<code>        //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);

</code>

迷茫迷茫2816 Il y a quelques jours597

répondre à tous(1)je répondrai

  • ringa_lee

    ringa_lee2017-04-17 11:15:48

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

    1

    2

    <code>headers = curl_slist_append(headers,"Accept-Encoding: gzip, deflate");

    </code>

    répondre
    0
  • Annulerrépondre