简体   繁体   English

无法使用 C++ 中的 libcurl 发送 JSON 请求

[英]Not able to send a JSON request using libcurl in C++

I am trying to access a GraphQL server with C++ and I am using the libcurl library to make the HTTP Post request.我正在尝试使用 C++ 访问 GraphQL 服务器,并且我正在使用 libcurl 库发出 HTTP 发布请求。

I got started with libcurl after reading the docs and I was testing the requests that were created using a test endpoint at hookbin.com阅读文档后,我开始使用 libcurl,我正在测试使用 hookbin.com 的测试端点创建的请求

Here is the sample code:这是示例代码:

int main(int argc, char* argv[]) {
    CURL* handle = curl_easy_init();
    curl_easy_setopt(handle, CURLOPT_URL, "https://hookb.in/YVk7VyoEyesQjy0QmdDl");

    struct curl_slist* headers = NULL;
    headers = curl_slist_append(headers, "Accept: application/json");
    headers = curl_slist_append(headers, "Content-Type: application/json");
    headers = curl_slist_append(headers, "charset: utf-8");
    curl_easy_setopt(handle, CURLOPT_HTTPHEADER, headers);

    string data = "{\"hi\" : \"there\"}";

    cout << data << endl;
    curl_easy_setopt(handle, CURLOPT_POSTFIELDS, data);

    CURLcode success = curl_easy_perform(handle);
    return 0;
}

When I send this post request I expect the request body to be the json {"hi": "there"} but I get some weird nonsense in the body.当我发送这个帖子请求时,我希望请求正文是 json {"hi": "there"} 但我在正文中得到了一些奇怪的废话。 Here is what the request body looks like:请求正文如下所示:

在此处输入图像描述

Why is this happening?为什么会这样? How do I fix this?我该如何解决?

curl_easy_setopt is a C function and can't deal with std::string data and CURLOPT_POSTFIELDS expects char* postdata . curl_easy_setopt是 C function 并且不能处理std::string dataCURLOPT_POSTFIELDS需要char* postdata Call std::string::c_str() for getting char* .调用std::string::c_str()以获取char*

curl_easy_setopt(handle, CURLOPT_POSTFIELDS, data.c_str());

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

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