使用https获取网站来源,使用cURL

时间:2016-02-06 18:56:44

标签: curl

我想获取网站HTML代码。 我正在使用的代码是

static size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream)
{
  int written = fwrite(ptr, size, nmemb, (FILE *)stream);
  return written;
}

int main(void)
{
  CURL *curl_handle;
  static const char *headerfilename = "head.txt";
  FILE *headerfile;
  static const char *bodyfilename = "body.txt";
  FILE *bodyfile;

  curl_global_init(CURL_GLOBAL_ALL);

          curl_handle = curl_easy_init();

    curl_easy_setopt(curl_handle, CURLOPT_URL, "http://www.chess.com");

          curl_easy_setopt(curl_handle, CURLOPT_NOPROGRESS, 1L);

  curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, write_data);
    curl_easy_setopt(curl_handle,CURLOPT_FOLLOWLOCATION,1);

  headerfile = fopen(headerfilename,"w");
  if (headerfile == NULL) {
    curl_easy_cleanup(curl_handle);
    return -1;
  }
  bodyfile = fopen(bodyfilename,"w");
  if (bodyfile == NULL) {
    curl_easy_cleanup(curl_handle);
    return -1;
  }
   curl_easy_setopt(curl_handle,   CURLOPT_WRITEDATA, headerfile);

  curl_easy_perform(curl_handle);
            fclose(headerfile);

  curl_easy_cleanup(curl_handle);
      return 0;
}

此代码适用于谷歌(使用http),但不适用于chess.com(使用https)。 我怎样才能让它为两者工作?

1 个答案:

答案 0 :(得分:0)

将以下内容添加到curl代码中:

curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYHOST, 0);
curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYPEER, 0);