【2022工作】【httplib工作记录】【使用curl Post 上传文件】

注意http和https使用的区别
https需要加
#define CPPHTTPLIB_OPENSSL_SUPPORT

登录:

bool vcPostUDCloud::Post_Token(const std::string& account, const std::string& password)
{
  httplib::SSLClient cli("域名", 443);  
  httplib::Params params;  //form-data 也是设置Params 
  params.emplace("account", account);
  params.emplace("password", password);
  auto res = cli.Post("url地址", params);
  if (res && res.error() == httplib::Error::Success)
  {
    httplib::Response value = res.value();
   }
}

【libcurl C++ post 上传文件】直接从postman代码块抄过来就可以

size_t write_data(void* buffer, int size, int nmemb, void* userp) {
  std::string* str = dynamic_cast<std::string*>((std::string*)userp);
  str->append((char*)buffer, size * nmemb);
  return nmemb;
}

string response;
string url = "你的url";

    CURL* curl;
    CURLcode ret;
    curl = curl_easy_init();
    struct curl_httppost* post = NULL;
    struct curl_httppost* last = NULL;
    if (curl)
    {
      curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
      curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
      struct curl_slist* headers = NULL;

      headers = curl_slist_append(headers, "token: 3fdf928b-3b18-40bb");
      
      curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
      curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);

      curl_easy_setopt(curl, CURLOPT_URL, (char*)url.c_str());           //指定url
  

      curl_formadd(&post,

        &last,

        CURLFORM_COPYNAME, "file",

        CURLFORM_FILE, mypath.c_str(),

        CURLFORM_FILENAME, "myfile.png",

        CURLFORM_END);


      curl_easy_setopt(curl, CURLOPT_HTTPPOST, post);                     //构造post参数    
     curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
      curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)response);        //绑定响应内容的地址

      ret = curl_easy_perform(curl);                          //执行请求
      string resultstr = UtfToGbk(response->c_str());

      if (ret == 0) {
        curl_easy_cleanup(curl);
        return 0;
      }
      else {
        return ret;
      }
    }
    else {
      return -1;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值