【Windows】【Demo】【C++】Curl

168 阅读2分钟

我正在参加「掘金·启航计划」

Curl 从下载到编译使用的教程!

[toc]

1、编译及使用

1.1 编译

1.1.1下载

GitHub - curl/curl: A command line tool and library for transferring data with URL syntax, supporting DICT, FILE, FTP, FTPS, GOPHER, GOPHERS, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, MQTT, POP3, POP3S, RTMP, RTMPS, RTSP, SCP, SFTP, SMB, SMBS, SMTP, SMTPS, TELNET and TFTP. libcurl offers a myriad of powerful features

点击链接下载,也可以使用git clone到本地

git clone https://github.com/curl/curl.git

1.1.2 编译

  • 方法一 VS编译器

如果需要使用vs编译,首先运行 project 目录下的 generate.bat 文件。然后在projects/Windwows 目录下打开对应的解决方案即可

  • 方法二 nmake

在下载目录 winbuild 目录下,查看 README.md ,里边告诉了我们如何编译自己需要的包,以我本人使用的为例。

  1. 打开对应版本的vs命令行工具

Config.png

  1. 进入对应的编译目录 curl-src\winbuild,接着执行以下命令就好。具体的命令参数可以查看winbuild目录下的介绍,选择自己需要的环境就好。
nmake /f Makefile.vc mode=dll vc=15 MACHINE=x86
  1. 执行以后就能在根目录 build 下看到生成了对应的文件夹,这时候就可以在项目中使用了。注意生成目录下有 bin、include、lib 三个文件夹。

1.2 使用

将生成的文件拖动到项目所在文件夹目录下,这时候需要做以下几个步骤,打开项目的属性页面:

1.2.1 预处理器

在预处理器中添加以下字段:

;BUILDING_LIBCURL;HTTP_ONLY;

1.2.2 附加库

  1. 在链接器中附加库目录,把lib文件夹添加到附加库目录当中

  2. 添加lib文件

    libcurl_a.lib;Ws2_32.lib;Wldap32.lib;winmm.lib;Crypt32.lib;Normaliz.lib;%(AdditionalDependencies)
    

1.3.3 使用

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

string UriHelper::Encode(const string& source)
{
	CURL* curl = curl_easy_init();
	char* cres = curl_easy_escape(curl, source.c_str(), source.length());
	string res(cres);
	curl_free(cres);
	curl_easy_cleanup(curl);
	return res;
}

int main()
{
    std::cout << "Hello World!\n";

    std::cout << Encode(R"(https://10.92.4.117:8443/tac
        /download/client/com.qianxin.trustagent.win.standard.exe.bm-3.1.1.4585/
        TrustAgent_standard_3.1.1.4585.aef031d09[10.92.4.117@443].exe)") << std::endl;
}
输出:
http0.0000000.0000000.000000www.baidu.com0.000000s0.000000ie%3Dutf-8 0.000000%3D8 %3Dbaidu%26wd%3D5.185438E-3164%B8%B48.694087E-3156%97%B65.190920E-3169%820.000000E5.12199E-31670.000000E%B1