command line option is working,below is the wokring request
命令行选项正在工作,下面是wokring请求
curl -s -H "Content-Type: application/json" https://speech.googleapis.com/v1/speech:recognize?key=apikey -d @sync-request.json
The same iam trying to do using libcurl ,Adding json data file is getting failed... Working when directly pass json data as string in curl::PostFields.
使用libcurl和添加json数据文件的操作也失败了……在curl:::PostFields中直接将json数据作为字符串传递时工作。
apikey replaced with mydev key on below example. for large file size need this option.
在下面的示例中,apikey替换为mydev key。对于较大的文件大小需要此选项。
#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;
}
throws error
抛出错误
<p>The requested URL <code>/v1/speech:recognize?key=apikey</code> was not found on this server.
1 个解决方案
#1
0
If you load your Json file content into a string, you can simply set your data as POST payload.
如果将Json文件内容加载到字符串中,只需将数据设置为POST有效负载。
string payload = json.data();
[...]
request.setOpt(new curlpp::options::PostFields(payload));
request.setOpt(new curlpp::options::PostFieldSize(payload.length()));
[...]
request.perform();
#1
0
If you load your Json file content into a string, you can simply set your data as POST payload.
如果将Json文件内容加载到字符串中,只需将数据设置为POST有效负载。
string payload = json.data();
[...]
request.setOpt(new curlpp::options::PostFields(payload));
request.setOpt(new curlpp::options::PostFieldSize(payload.length()));
[...]
request.perform();