当前位置: 首页 > 工具软件 > HttpLib > 使用案例 >

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

计燕七
2023-12-01

注意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;
    }
 类似资料: