我正在尝试使用C++访问GraphQL服务器,并且正在使用libcurl库发出HTTP Post请求。
我在阅读了文档之后开始使用libcurl,并在www.example.com上测试了使用测试端点创建的请求hookbin.com
下面是示例代码:
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;
}
当我发送这个post请求时,我希望请求主体是json {“hi”:“there”}但是我在主体中得到了一些奇怪的无意义的东西。下面是请求主体的样子:
为什么会这样?我该怎么解决?
1条答案
按热度按时间h4cxqtbf1#
curl_easy_setopt
是一个C函数,无法处理std::string data
,而CURLOPT_POSTFIELDS
需要char* postdata
。调用std::string::c_str()
以获取char*
。