C++ 之libcurl网络通讯

官网没有编译好的libcurl库所以需要手动下载然后编译生成libcurl.lib【开发环境win10+vs2017】  

下载方式以及版本如图所示:

 

下载完成解压:

VS控制台进入D:\curl-7.85.0\winbuild

 

 

 

编译命令: nmake /f Makefile.vc mode=static VC=15 MACHINE=x64 DEBUG=no

  • 如需动态编译,将 mode=static 改为 mode=dll。(本文仅演示静态编译,同时 curl 官方也不建议使用动态编译)
  • 如需编译为 x86,将 MACHINE=x64 改为 MACHINE=x86。
  • 如需编译为debug版,将DEBUG=no改为DEBUG=yes。
  • 如果你是 VS2019,VC=15 建议改为 VC=14。
  • 更详细的编译指令及说明可以打开 winbuild 文件夹中的 BUILD.WINDOWS.txt 查看

编译完成对应的dll或者lib,本文生成的是lib

 

 

     加载 lib +.h来使用 libcurl  

 

新建一个libcurlDemo的工程,把生成的libcurl连接进来配置如下:

一、配置头文件以及lib目录

 

 二、libcurl_a.lib

        Ws2_32.lib

        Wldap32.lib

        winmm.lib

        Crypt32.lib

        Normaliz.lib全都加载到工程缺少则会报链接错误

  

 

BUILDING_LIBCURL
HTTP_ONLY

添加预处理:

 

 

 

解决MSVC 库冲突

 /NODEFAULTLIB:"libcmt.lib" 

 

 

 

运行时库选择:

使用了静态编译且没有编译debug版libcurl选择为/MD
如果编译了debug版libcurl,请分别在Configurations: Debug中选择/MDd、Configurations: Release中选择/MD
如果使用了动态编译,则为/MTd/MT

三、测试代码 

 

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

using namespace std;

int main()
{

  CURL* curl = nullptr;
  CURLcode res;

  curl = curl_easy_init();
  if (curl != nullptr) {

    curl_easy_setopt(curl, CURLOPT_URL, "https://fanyi.baidu.com/");

    /* example.com is redirected, so we tell libcurl to follow redirection */
    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);

    /* Perform the request, res will get the return code */
    res = curl_easy_perform(curl);

    /* Check for errors */
  if (res != CURLE_OK) {
    fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
    }
    /* always cleanup */
    curl_easy_cleanup(curl);
  }

  system("pause");
  return 0;
}

 

打印网页的内容到控制台,则说明libcurl正确加载并能使用。UTF8中文乱码

 

参考博客:

https://www.cnblogs.com/linuxAndMcu/p/14723778.html

 

posted on 2022-10-20 15:19  流若浅  阅读(339)  评论(0编辑  收藏  举报

导航