Curl添加open ssl 实现https连接

Curl默认是不包含open ssl的,需要手动添加依赖项并修改编译参数。

1.从http://curl.haxx.se下载最新的curl源码,github应该也有,或者从我的下载连接下载也可以:

http://download.csdn.net/detail/sirria1/9579061

2.从http://windows.php.net/downloads/php-sdk/deps/网站下载相关的open ssl文件,或者从我的下载连接下载也可以:

http://download.csdn.net/detail/sirria1/9579063

3.将下载的open ssl 文件拷贝到curl的同级目录,参考 curl-7.49.1\curl-7.49.1\winbuild\BUILD.WINDOWS.txt 这个文档的说明

  If you wish to support zlib, openssl, c-ares, ssh2, you will have to download
    them separately and copy them to the deps directory as shown below:
   
    somedirectory\
    |_curl-src
    | |_winbuild
    |
    |_deps
      |_ lib
      |_ include
      |_ bin

   It is also possible to create the deps directory in some other random
   places and tell the Makefile its location using the WITH_DEVEL option.


4.进入 curl-7.49.1\curl-7.49.1\winbuild 目录创建一个编译bat,内容如下:

@REM @echo off
@IF [%1]==[debug] (
@echo 正在使用debug模式编译libcurl~~~
@nmake /f Makefile.vc WITH_DEVEL=../../openssl-1.0.1t-vc11-x86 mode=static VC=12 WITH_SSL=static ENABLE_IDN=no RTLIBCFG=dll DEBUG=yes MACHINE=x86
) ELSE (
@echo 正在使用release模式编译libcurl~~~
@nmake /f Makefile.vc WITH_DEVEL=../../openssl-1.0.1t-vc11-x86 mode=static VC=12 WITH_SSL=static ENABLE_IDN=no RTLIBCFG=dll DEBUG=no MACHINE=x86
)
@REM @echo on

编译参数说明可以参考同目录下的文档:BUILD.WINDOWS.txt


5.点击 开始->所有程序 找到VS2012版本 以上的目录文件  点击 【visual studio tools】运行VS20xx 开发人员命令提示 让后进入到你的curl-7.49.1\curl-7.49.1\winbuild

这个目录,运行 第四步创建的bat,带debug参数就会编译出 debug版。


这样编译得到的curl库就能拉取https网站数据了。


代码示例

#include "stdafx.h"
#include "curl/curl.h"
#include <iostream>

#pragma comment(lib, "libcurl_a_debug.lib")

using namespace std;

size_t WriteFunc(char *data, size_t size, size_t nmemb, void* s)
{
	int len = fwrite(data, size, nmemb, (FILE*)s);
	return len;
}

bool getUrl(char *filename)
{
	CURL *curl;
	CURLcode res = CURL_LAST;
	FILE *fp;
	errno_t err = fopen_s(&fp, filename, "w");
	if (0 != err)
	{
		return false;
	}
	string strReturnBuffer;
	int nCurlResultCode = 0;
	curl = curl_easy_init();    // 初始化
	if (curl)
	{
		int nCount = 0;
		while (0 != res && nCount++ < 50)
		{
			curl_easy_setopt(curl, CURLOPT_URL, "https://www.baidu.com/");
			curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
			curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &WriteFunc);
			curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
			curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);	// 禁用证书验证
			res = curl_easy_perform(curl);   // 执行
		}

		if (res != CURLE_OK) {

			fprintf(stderr, "curl_easy_perform error:%s\n", curl_easy_strerror(res));
		}
		curl_easy_cleanup(curl);
		fwrite(strReturnBuffer.c_str(), strReturnBuffer.size(), 1, fp);
		fclose(fp);
		return true;
	}

	return false;
}

int _tmain(int argc, _TCHAR* argv[])
{
	getUrl("get.html");
	return 0;
}





猜你喜欢

转载自blog.csdn.net/sirria1/article/details/51941761