libcurl 如何支持https
执行curl_easy_perform()的时候,返回错误代码:CURLE_UNSUPPORTED_PROTOCOL(1),同时通过打印日志会得到错误提示:" Protocol https not supported or disabled in libcurl"。意思是:不支持HTTPS协议!有人说添加下面两行代码就可以解决:
curl_easy_setopt(curl,CURLOPT_SSL_VERIFYPEER,false);//设定为不验证证书和HOST
curl_easy_setopt(curl,CURLOPT_SSL_VERIFYHOST,false);
测试发现,还是不能支持HTTPS访问!此时,如果还是无法访问HTTPS的网页的话,问题可能出在libcurl本身,很可能是 libcurl 在编译的时候没有选择支持SSL,所以还是重新编译一次libcurl吧!这里要提醒大家的是,通过用CMake工具生成的sln文件来直接编译lib库(我之前就是这样编译的),也很可能没有做SSL支持。所以还是用命令行工具来编译,先制作一个build.bat文件,待会要用到,内容如下:
@REM @echo off @IF [%1]==[debug] ( @echo 正在使用debug模式编译libcurl~~~ @nmake /f Makefile.vc WITH_DEVEL=../../deps mode=static VC=12 ENABLE_IDN=no RTLIBCFG=dll DEBUG=yes MACHINE=x86 ) ELSE ( @echo 正在使用release模式编译libcurl~~~ @nmake /f Makefile.vc WITH_DEVEL=../../deps mode=static VC=12 ENABLE_IDN=no RTLIBCFG=dll DEBUG=no MACHINE=x86 ) @REM @echo on
本人下载的是7.48.0版本,接着在开始菜单中打开Visual Studio 2013 > Visual Studio Tools > VS2013开发人员命令提示,cd到curl-7.48.0的winbuild目录下:输入build.bat 按下回车键开始编译,等待编译完成!如果是debug版本,则再输入空格 debug,回车!开始编译。。。最后,贴上一段使用libcurl进行https访问的代码,希望对大家有所帮助。
int https_get(const std::string & strUrl, std::string & strResponse, const char * pCaPath) { CURLcode res; CURL* curl = curl_easy_init(); if(NULL == curl) { return CURLE_FAILED_INIT; } curl_easy_setopt(curl, CURLOPT_URL, strUrl.c_str()); curl_easy_setopt(curl, CURLOPT_READFUNCTION, NULL); curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&strResponse); curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1); if(NULL == pCaPath) { curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);//设定为不验证证书和HOST curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, false); } else { curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, true); curl_easy_setopt(curl, CURLOPT_CAINFO, pCaPath); } curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 3); curl_easy_setopt(curl, CURLOPT_TIMEOUT, 3); res = curl_easy_perform(curl); curl_easy_cleanup(curl); return res; }
PS:使用libcurl作为http客户端,可以参考一下:http://blog.csdn.net/hellokandy/article/details/53911448