[英]Passing multiple POST request parameters C++ libcurl
目前使用 libcurl 的 C++ 實現與 Spotify API 交互,尋找在 POST 請求期間傳遞多個“請求正文參數”的方法。 必填字段為:
查看 libcurl 文檔中的 POST 請求示例,似乎這一行:
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "name=daniel&project=curl");
傳遞兩個參數:“名稱”和“項目”。 當我使用 Spotify 的 API 嘗試類似的格式時:
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "grant_type=authorization_code&code=abcdef&redirect_uri=example.com");
我收到以下錯誤:
{"error":"unsupported_grant_type","error_description":"grant_type parameter is missing"}
我已經通過僅傳遞"grant_type"
驗證了CURLOPT_POSTFIELDS
適用於這種情況,因為 API 響應告訴我我的請求缺少代碼,因此很明顯 API 正在讀取POSTFIELDS
參數。
有人對如何在POST
請求中包含多個參數有任何見解嗎?
編輯:提供一個最小的可重現示例:作為 oAuth 流程的一部分,此示例發生在用戶收到 oAuth 訪問令牌之后
CURL *curl;
std::string res;
curl = curl_easy_init();
if(curl) {
try {
curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 0);
curl_easy_setopt(curl, CURLOPT_URL, "https://accounts.spotify.com/api/token");
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "grant_type=authorization_code&code=abcdef&redirect_uri=example.com");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &res);
std::string enc = base64_encode(reinterpret_cast<const unsigned char*>((myClientID + ":" + myClientSecret).data()), (myclientID + ":" + myClientSecret).length(), false);
std::string httpAuth = "Authorization: Basic " + enc;
struct curl_slist *authChunk = nullptr;
authChunk = curl_slist_append(authChunk, httpAuth.c_str());
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, authChunk);
curl_easy_perform(curl);
curl_easy_cleanup(curl);
}
catch (const char* Exception) {
std::cerr << Exception << std::endl;
}
}
對於遇到此問題的任何人 - 確保在格式化POST
請求時正確編碼redirect_uri
參數。 這是我做的不同
// Wrote a custom URL encoding function
std::string urlEncEasy(std::string url) {
std::string res;
for (auto c : url) {
if (c == ':') {
res += "%3A";
}
else if (c == '/') {
res += "%2F";
}
else {
res += c;
}
}
return res;
}
// Changed my CURLOPT_POSTFIELDS to
std::string postFields = "grant_type=authorization_code&code=" + myAuthToken + "&redirect_uri=" + urlEncEasy(myRedirectUri);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postFields.c_str());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.