【问题标题】:C++ libcurl http response code issuesC++ libcurl http响应代码问题
【发布时间】:2010-06-28 23:44:04
【问题描述】:

这个问题/怪癖/副作用让我发疯。在代码的底部附近,HTTP 交互的响应代码通过引用传递到 responseCode_。然而,即使该站点可以以其他方式访问,它也经常显示为 0,并且返回太快而无法超时...

定义了所有变量,下面的代码只是一个类中C++方法的sn-p。任何 var_ 变量都是基于实例的。它在多个线程上运行,但这应该不是问题。每个使用 libcurl 的类在各自的线程上都有自己的实例。

提前感谢您的任何想法或建议...

 CURL *curl;
 curl = curl_easy_init();
 //The URL
 curl_easy_setopt(curl, CURLOPT_URL, url.getURLString().c_str());
 //Timeout
 curl_easy_setopt(curl, CURLOPT_TIMEOUT, &timeout_);
 //disable signals to use with threads
 curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
 //Redirecting
 curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 5);
 curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
 //Writing callback
 curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, &writerh);
 curl_easy_setopt(curl, CURLOPT_HEADERDATA, &head_);
 //Writing callback
 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &writerb);
 curl_easy_setopt(curl, CURLOPT_WRITEDATA, &body_);
 //Headers
 struct curl_slist *headers = NULL;
 for (std::map<std::string, std::string>::iterator itr = requestHeaders_.begin(); itr != requestHeaders_.end(); itr++) {
  std::stringstream header;
  header << itr->first << ": " << itr->second;
  headers = curl_slist_append(headers, header.str().c_str());
 }
 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
 //UA
 curl_easy_setopt(curl, CURLOPT_USERAGENT, "RDFaS-Bot/1.0 (+http://www.rdfas.com/bot)");
 curl_easy_perform(curl); /* ignores error */
 //Response code
 curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &responseCode_);
 //clean headers
 curl_slist_free_all(headers);
 curl_easy_cleanup(curl);

更新:

curl_easy_perform 在响应代码为 0 时没有返回 CURLE_OK,正如标记的答案所解释的那样。但是调试钩子也非常有用,是一个很好的建议

【问题讨论】:

    标签: c++ http response libcurl


    【解决方案1】:

    只有当 curl_easy_perform() 返回 CURLE_OK 时才会设置响应代码,因此您应该首先检查以确保 curl 实际成功执行了请求。你确定写header和body的回调函数设置正确吗?

    另外,请确保在这些 easy_perform 线程启动之前调用 curl_global_init(CURL_GLOBAL_ALL)。

    假设 curl_easy_init() 返回的 curl 句柄中没有任何内容在线程间共享,那么代码看起来是正确的。

    【讨论】:

      【解决方案2】:

      使用 libcurl 内置的调试钩子。

      说真的。 libcurl 是void*s 和错误代码的“C”噩梦。 一切在使用 libcurl 时都可能出错。编写一次你的 libcurl 调试钩子,不要从你的代码中删除它们。你会一次又一次地需要它们,一次又一次,......一次又一次。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-12
        • 1970-01-01
        • 2017-12-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多