![](/img/trans.png)
[英]C++ - how to send a HTTP post request using Curlpp or libcurl
[英]Not able to send a JSON request using libcurl in C++
我正在嘗試使用 C++ 訪問 GraphQL 服務器,並且我正在使用 libcurl 庫發出 HTTP 發布請求。
閱讀文檔后,我開始使用 libcurl,我正在測試使用 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;
}
當我發送這個帖子請求時,我希望請求正文是 json {"hi": "there"} 但我在正文中得到了一些奇怪的廢話。 請求正文如下所示:
為什么會這樣? 我該如何解決?
curl_easy_setopt
是 C function 並且不能處理std::string data
和CURLOPT_POSTFIELDS
需要char* postdata
。 調用std::string::c_str()
以獲取char*
。
curl_easy_setopt(handle, CURLOPT_POSTFIELDS, data.c_str());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.