【问题标题】:cURL send POST data-binarycURL 发送 POST 数据二进制
【发布时间】:2020-11-02 10:00:17
【问题描述】:

我有 cURL 命令:

curl "https://pelevin.gpt.dobro.ai/generate/" --data-binary '{"prompt" : "text" , "length" : 40}

我想在 C++ 中做同样的事情。

我试过了:

  string params = "prompt=text&length=40";
  string buffer;
  CURL*  curl;
  curl = curl_easy_init();
  if (curl) {
    curl_easy_setopt(curl, CURLOPT_URL, "https://pelevin.gpt.dobro.ai/generate/");
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, params.size());
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, params.c_str());
    curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
    curl_easy_perform(curl);
  }
  curl_easy_cleanup(curl);

收到这样的消息:

{"detail":[{"loc":["body",0],"msg":"Expecting value: line 1 column 1 (char 0)","type":"value_error.jsondecode","ctx":{"msg":"Expecting value","doc":"prompt=text&length=40","pos":0,"lineno":1,"colno":1}}]}

如何正确提出请求?

【问题讨论】:

    标签: c++ curl libcurl


    【解决方案1】:

    当您从命令行转到 libcurl 时,您更改了您提供的数据。为什么?

    首先它是一个 JSON 对象字符串(这似乎是服务器所期望的)。现在你已经把它变成了一个 URL 编码的字符串。

    只需将正确的数据传递给服务器,就像您在第一个示例中所做的那样。

    string params = "{\"prompt\" : \"text\" , \"length\" : 40}";
    

    注意如果你愿意的话,在现代 C++ 中有“更好”的方式来格式化它:

    string params = R"RAW({"prompt" : "text" , "length" : 40})RAW";
    

    顺便说一句,将--data-binary 与命令行上指定的数据一起使用很奇怪。 It's intended for use with file input,因为它可以防止从文件中删除换行符。

    【讨论】:

      猜你喜欢
      • 2011-03-04
      • 2011-12-13
      • 1970-01-01
      • 2016-02-02
      • 1970-01-01
      • 2012-02-18
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      相关资源
      最近更新 更多