我正在嘗試使用 C 訪問 GraphQL 服務器,并且正在使用 libcurl 庫發出 HTTP Post 請求。
閱讀檔案后,我開始使用 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"} 但我在正文中得到了一些奇怪的廢話。請求正文如下所示:

為什么會這樣?我該如何解決?
uj5u.com熱心網友回復:
curl_easy_setopt是一個 C 函式,不能處理std::string data和CURLOPT_POSTFIELDS期望char* postdata. 要求std::string::c_str()獲得char*.
curl_easy_setopt(handle, CURLOPT_POSTFIELDS, data.c_str());
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/505198.html
