C++libcurl http响应代码问题 [英] C++ libcurl http response code issues

查看:97
本文介绍了C++libcurl http响应代码问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题/怪癖/副作用快把我逼疯了。在代码底部附近,通过引用将HTTP交互的响应代码传递给ResponseCode_。然而,它经常显示为0,即使该站点可以通过其他方式访问,并且返回得太快而导致超时...

所有变量都已定义,下面的代码只是类中C++方法的一小段。任何var_Variables都是基于实例的。它在多个线程上运行,但这应该不是问题。使用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,如标记答案所示。但是,调试挂钩也非常有用,也是一个很好的建议

推荐答案

只有在CURL_EASY_PERFORM()返回CURLE_OK时才会设置响应代码,因此您应该首先进行检查,以确保CURL确实成功执行了请求。您确定写入Header和Body的回调函数设置正确吗?

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

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

这篇关于C++libcurl http响应代码问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆