如何使用Curlpp编写json数据文件?

时间:2018-02-06 12:17:58

标签: c json libcurl curlpp

命令行选项正在运行,下面是wokring请求

curl -s -H "Content-Type: application/json"   https://speech.googleapis.com/v1/speech:recognize?key=apikey -d @sync-request.json

同样的iam尝试使用libcurl,添加json数据文件失败了...... 在curl :: PostFields中直接将json数据作为字符串传递时工作。

在下面的示例中,使用mydev键替换了 apikey。 对于大文件大小需要此选项。

#include <iostream>
 #include <curlpp/Options.hpp>
 #include <curlpp/Easy.hpp>
 #include <curlpp/cURLpp.hpp>
 #include <sstream>
 #include <future>
 #include <curlpp/Exception.hpp>
 #include <cstdlib>
 #include <cstdio>
 #include <cstring>
 #include <cerrno>

    size_t WriteCallback(char* ptr, size_t size, size_t nmemb, void *f)
    {
        FILE *file = (FILE *)f;
        cout<<"file write"<<endl;
        return fwrite(ptr, size, nmemb, file);
    }

    std::future<std::string> invoke(std::string const& url) {
      return std::async(std::launch::async, 
        [](std::string const& url) mutable {
          std::list<std::string> header;
          header.push_back("Content-Type: application/json");

          FILE* file = fopen("sync-request.json", "wb");
          curlpp::options::WriteFunctionCurlFunction  myFunction(WriteCallback);
          curlpp::OptionTrait<void *, CURLOPT_WRITEDATA> myData(file);

          curlpp::Cleanup clean;
          curlpp::Easy r;
          r.setOpt(new curlpp::options::Url(url));
          r.setOpt(new curlpp::options::HttpHeader(header));
          r.setOpt(myFunction);
          r.setOpt(myData);

          std::ostringstream response;
          r.setOpt(new curlpp::options::WriteStream(&response));

          r.perform();
          std::cout<<std::string(response.str());
          return std::string(response.str());
        }, url);
    }
    int main(int argc, char **argv) {
        invoke("https://speech.googleapis.com/v1/speech:recognize?key=apikey");
        return 0;
    }

抛出错误

  <p>The requested URL <code>/v1/speech:recognize?key=apikey</code> was not found on this server.

1 个答案:

答案 0 :(得分:1)

如果将Json文件内容加载到字符串中,则只需将数据设置为POST有效内容即可。

    string payload = json.data();
    [...]
    request.setOpt(new curlpp::options::PostFields(payload));
    request.setOpt(new curlpp::options::PostFieldSize(payload.length()));
    [...]
    request.perform();