C++ libcurl 不发布数据

标签 c++ curl

我正在开发一个 C++ 库,该库利用curl 库对 Web 服务执行 HTTP POST 请求。

我有一个函数负责执行curl并处理响应,并且该函数调用另一个函数来设置curl,因为它可以在具有相同设置的多个地方使用。

它成功连接到网络服务,我可以看到返回的响应,但是没有发布数据发送到网络服务。

下面的代码是我必须执行 HTTP 请求的代码。

第一个函数是curl执行的函数,它调用一个函数来初始化curl库,然后返回指向它的指针以供使用。

string response;
struct curl_slist *list = NULL;
const char * jsonString = ddEvent.getDDEventAsJSONString().c_str();
CURL *curl = this->initCurl(ddEvent, &response, list, &jsonString);
if (curl == NULL)
{
    return false;
}

list = curl_slist_append(list, "Content-Type: application/json");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, list);
CURLcode res = curl_easy_perform(curl);

初始化curl的函数如下:

CURL * MyClass::initCurl(DDEvent ddEvent, string *response, struct curl_slist *list, const char **jsonString)
{
    CURL *curl = NULL;

    curl = curl_easy_init();
    if (curl == NULL)
    {
        cout << "Failed to initialise curl" << endl;
        return NULL;
    }
    stringstream url_stream;
    url_stream << "http://192.168.1.123";
    string url= dd_url_stream.str();

    cout << "Using URL: " << url<< endl;

    curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1);
    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 1);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, response);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &MyClass::curlResponseWriteCallback);
    curl_easy_setopt(curl, CURLOPT_HEADER, 1);
    curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
    curl_easy_setopt(curl, CURLOPT_POST, 1);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, *jsonString);

    return curl;
}

此外,发布数据是一个 JSON 字符串,它不是发布表单数据的键/值。

下面是curl详细模式的输出

Using JSON string {"title":"HTTP Event Teesg","text":"Test warning event","alert_type":"success","tags":["simple_string_tag"]}
Using URL: http://192.168.1.123
* About to connect() to 192.168.1.123 port 80 (#0)
*   Trying 192.168.1.123...
* Connected to 192.168.1.123 (192.168.1.123) port 80 (#0)
> POST / HTTP/1.1
Host: 192.168.1.123
Accept: */*
Content-Type: application/json
Content-Length: 0

< HTTP/1.1 200 OK
< Date: Sun, 04 Feb 2018 20:11:12 GMT
< Server: Apache/2.4.6 (CentOS) PHP/5.6.32
< X-Powered-By: PHP/5.6.32
< X-XSS-Protection: 1; mode=block
< Content-Length: 52
< Content-Type: text/html; charset=UTF-8
<

最佳答案

传出请求中的 Content-Length: 0 表明您传递给 CURLOPT_POSTFIELDS 的数据长度为零。

请注意,CURLOPT_POSTFIELDS 不会复制数据,它只是指向您的内存,因此您可能需要确保数据在 libcurl 需要的整个时间内仍然存在。由于您没有向我们展示整个程序,我们无法真正告诉您这是如何发生的。

最后:为什么不直接将“char *”传递给 initCurl 而不是需要在方法内取消引用的“char **”?我觉得很奇怪。

关于C++ libcurl 不发布数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48612613/

相关文章:

php - 使用 Curl PhP5.6 而不是 Curl PhP7

cURL 不适用于 nghttp2

c++ - "real-time"约束是否会阻止使用任务计划程序?

c++ - 缺少 Visual Studio Express 2012 tracker.exe

c++ - 是否应该在 C++ 头文件中初始化 const 静态变量?

ruby - 将原始代码从 github 管道传输到 ruby​​ 不起作用?

bash - 为 http 响应中的每一行添加换行符

c++ - 如何有效地在 vector 中插入多个可复制构造但不可复制分配的元素?

c++ - 将 FBO 混合到默认帧缓冲区

bash - curl 命令中的 $'{}' 是什么意思