我正在尝试获取使用 curl.h 库的 C++ 代码来发出需要设置 Authorization: Bearer header 的 curl 请求。我正在使用 Linux Mint 18 (Ubuntu)。
我从命令行发出了这个 curl 请求,它有效,看起来像这样:
curl -H "Content-Type: application/json" -H "Authorization: Bearer <my_token>" <my_url>
这样做会返回一个有效的结果。
但是,我尝试使用 curl.h 库在 C++ 中为此编写等效代码,但我得到了 {"errorMessage":"Insufficient authorization to perform request."
这是我使用的 C++ 代码:
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <string>
#include <curl/curl.h>
using namespace std;
int main(int argc, char** argv)
{
CURL* curl = curl_easy_init();
if (!curl) {
cerr << "curl initialization failure" << endl;
return 1;
}
CURLcode res;
// the actual code has the actual url string in place of <my_url>
curl_easy_setopt(curl, CURLOPT_URL, <my_url>);
struct curl_slist* headers = NULL;
curl_slist_append(headers, "Content-Type: application/json");
// the actual code has the actual token in place of <my_token>
curl_slist_append(headers, "Authorization: Bearer <my_token>");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
res = curl_easy_perform(curl);
if (res != CURLE_OK) {
cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << endl;
}
curl_easy_cleanup(curl);
return 0;
}
我也尝试过使用如下所示的一行:
curl_easy_setopt(curl, CURLOPT_XOAUTH2_BEARER, <my_token>);
代替这一行:
curl_slist_append(headers, "Authorization: Bearer <my_token>");
我也曾尝试在 curl_easy_perform
之前添加这些行:
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
和
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
因为我在四处搜索时看到了那些线条
但我为弄清楚如何使这项工作所做的所有努力仍然给我留下“错误消息:执行请求的授权不足。”
是的,顺便说一句,我已经确保我使用的 url 和 token 都是正确的。
我做错了什么,以及如何将顶部的命令行代码正确转换为等效的 C++ 代码。
最佳答案
您需要在每次调用中将 curl_slist_append()
的返回值分配给 headers
:
headers = curl_slist_append(headers, "Content-Type: application/json");
headers = curl_slist_append(headers, "Authorization: Bearer <my_token>");
参见 this doc
您调用它的方式 headers
将始终保持为 NULL,这就是您传递给 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
关于c++ - 如何在 C++ curl 代码中设置授权承载 header ?我获得的授权不足,尽管它在命令行下有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51540741/