简体   繁体   English

在 C++/C 中使用 CURL 发出带有数据文件的 GET HTTP 请求

[英]Using CURL in C++/C to issue a GET HTTP Request with a data file

Using the CURL at the command line:在命令行中使用 CURL:

curl -d @%1 -X GET https://blah-blah curl -d @%1 -X GET https://blah-blah

This is in a Windows batch file and I pass the name of the file on the command line.这是在 Windows 批处理文件中,我在命令行上传递了文件的名称。 Using this, I can issue a service call sending in a file with a whole lot of input parameters and I receive a substantial output.使用它,我可以在包含大量输入参数的文件中发出服务调用,并收到大量的 output。

For the life of me, when I try pro \grammatically, I can't make it work.对于我的生活,当我尝试编程时,我无法让它工作。 It must be possible, since it can be done on the command.它必须是可能的,因为它可以在命令上完成。 However, when I set但是,当我设置

curl_easy_setopt(m_Curl, CURLOPT_HTTPGET, 1);

I can't upload a file, even if I set the callback即使我设置了回调,我也无法上传文件

If I use:如果我使用:

curl_easy_setopt(m_Curl, CURLOPT_UPLOAD, 1L);

the call becomes 'PUT', even though I try and force the header to be a GET.即使我尝试强制 header 成为 GET,调用也会变为“PUT”。 I follow the documentation and can see that this is the documented behavior.我遵循文档,可以看到这是记录在案的行为。 However, what is the pathway for avoiding this default?但是,避免这种默认的途径是什么?

Any guidance would be most appreciated.任何指导将不胜感激。

Thanks,谢谢,

Stan斯坦

AFAIK it's not strictly forbidden but you shouldn't send a body with a GET request. AFAIK 这不是严格禁止的,但您不应该发送带有 GET 请求的正文。 On the other side a server should be able to handle a GET request with body but the response shouldn't be dependent of the content of the body.另一方面,服务器应该能够处理带有正文的 GET 请求,但响应不应依赖于正文的内容。

If you really need to send a request containing a body with GET you can change the value of the method with CURLOPT_CUSTOMREQUEST .如果您确实需要使用 GET 发送包含正文的请求,您可以使用CURLOPT_CUSTOMREQUEST更改方法的值。 This won't change the behavior of curl.这不会改变 curl 的行为。 This snippet will upload data with GET:此代码段将使用 GET 上传数据:

  CURL* curl = curl_easy_init();
  if (curl) {
    curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
    curl_easy_setopt(curl, CURLOPT_URL, url);
    curl_easy_setopt(curl, CURLOPT_PORT, port);
    curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "GET");

    const auto* file = fopen(filename.c_str(), "r");
    curl_easy_setopt(curl, CURLOPT_READDATA, file);
    curl_easy_setopt(
        curl, CURLOPT_INFILESIZE_LARGE, static_cast<curl_off_t>(filesize));

    curl_easy_perform(curl);
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM