c++httprequestcurlpp

How to upload file and json data with method POST use curlpp


I want to write C++ code with using curlpp library which work exactly as following example on curl if it possible of course.

> 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
>

I was able to write transfer json text with method POST but when I added upload command this library substitute PUT instead of POST.


Solution

  • I decided to post answer here, perhaps it will help somebody like me

    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());
    
    }