cURL重新连接到同一个网址

时间:2014-10-16 15:29:10

标签: c++ curl

当我尝试连接到新网址时,我需要使用新网址运行程序,程序无法连接,当我重新启动程序时,它将连接。

所以我要做的是重置,所有连接而不是重新启动程序只是尝试连接到url一次然后重置连接并重新连接,导致与重新启动程序相同的效果。

有没有办法做到这一点?是什么原因导致我的程序无法加载新的URL?并强迫我重新启动程序以使其工作?

这是我的代码:

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

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

int main(void)
{
 std::ofstream file("source.txt");
 CURL *curl;
 CURLcode res = CURL_LAST;
 std::string readBuffer;

 curl = curl_easy_init();
 while (curl && res != CURLE_OK){

  curl_easy_setopt(curl, CURLOPT_URL, "http://www.example.com/");
  curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, true);
  curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
  curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
  curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 5);
  curl_easy_setopt(curl, CURLOPT_TIMEOUT, 5);
  curl_easy_setopt(curl, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)");
  curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
  curl_easy_setopt(curl, CURLOPT_VERBOSE, true);
  res = curl_easy_perform(curl);
  curl_easy_cleanup(curl);
  if (res != CURLE_OK)
   curl = curl_easy_init();
 }
 file << readBuffer;
 file.close();
 std::cout << readBuffer << std::endl;
 std::cin.ignore();
 return 0;
}

这里我尝试使用while循环重新连接并尝试使用 curl_easy_init()重置连接

0 个答案:

没有答案