c++ - 如何使用 curlpp 方法使用 POST 上传文件和 json 数据

标签 c++ httprequest curlpp

我想使用 curlpp 库编写 C++ 代码,如果可能的话,它在 curl 上的工作方式与以下示例完全相同。

> curl -H "Content-Type: application/json" -X POST -d '{"param1":"val1", "param2":"val2", "param3":"val3"}' --data-binary '@/tmp/somefolder/file.bin' https://my-api.somedomain.com:1024/my_command_url
>

我能够使用 POST 方法编写传输 json 文本,但是当我添加上传命令时,这个库用 PUT 代替了 POST。

最佳答案

我决定在这里发布答案,也许它会帮助像我这样的人

static string post_request(const string url,const string body1,const string path2file)
{
   const string field_divider="&";
   stringstream result;
   try
   {
      using namespace std;

      // This block responsible for reading in the fastest way media file
      //      and prepare it for sending on API server
      ifstream is(path2file);
      is.seekg(0, ios_base::end);
      size_t size=is.tellg();
      is.seekg(0, ios_base::beg);
      vector<char> v(size/sizeof(char));
      is.read((char*) &v[0], size);
      is.close();
      string body2(v.begin(),v.end());

      // Initialization
      curlpp::Cleanup cleaner;
      curlpp::Easy request;
      list< string > headers;
      headers.push_back("Content-Type: application/json");
      headers.push_back("User-Agent: curl/7.77.7");

      using namespace curlpp::Options;

      request.setOpt(new Verbose(true));
      request.setOpt(new HttpHeader(headers));
      request.setOpt(new Url(url));
      request.setOpt(new PostFields(body1+field_divider+body2));
      request.setOpt(new PostFieldSize(body1.length()+field_divider.length()+body2.length()));
      request.setOpt(new curlpp::options::SslEngineDefault());
      request.setOpt(WriteStream(&result));
      request.perform();
   }
   catch ( curlpp::LogicError & e )
     {
       cout << e.what() << endl;
     }
   catch ( curlpp::RuntimeError & e )
     {
       cout << e.what() << endl;
     }

   return (result.str());

}

关于c++ - 如何使用 curlpp 方法使用 POST 上传文件和 json 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53091611/

相关文章:

c# - 从 C++ 编码到 C# 时 CLR 崩溃

c++ - 在 C++ 中调用内部类成员的情况下是否应该使用 -> 运算符?

javascript - 用于 api 测试的 testcafe - 如何使用自定义 requesthook 验证响应代码

c++ - Curlpp 的问题

c++ - 体系结构 x86_64 (curlpp) 的 undefined symbol

c++ - 警告 : control reaches end of non-void function [-Wreturn-type]

c++ - 数组 C++ 上没有打印任何内容

java - HttpServletRequest getParameter 无法使用 & 检索参数

css - @import vs <link> vs 单体 css

c++ - 在 dll 文件中包含 C++ 的 curl 库