[英]How do I set authorization bearer header in C++ curl code? I'm getting insufficient authorization, eventhough it works at the command line
我正在尝试获取使用 curl.h 库的 C++ 代码来发出需要设置 Authorization: Bearer 标头的 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 和令牌都是正确的。
我做错了什么,如何将顶部的命令行代码正确转换为等效的 C++ 代码。
您需要在每次调用curl_slist_append()
的返回值分配给headers
,如下所示:
headers = curl_slist_append(headers, "Content-Type: application/json");
headers = curl_slist_append(headers, "Authorization: Bearer <my_token>");
请参阅此文档
您调用它的方式headers
将始终保持为 NULL,这就是您传递给curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
我对CURLOPT_XOAUTH2_BEARER
有同样的问题。 解决方案是将CURLOPT_HTTPAUTH
为CURLAUTH_BEARER
,如下所示:
curl_easy_setopt(curl, CURLOPT_XOAUTH2_BEARER, "<my_token>");
curl_easy_setopt(_connection, CURLOPT_HTTPAUTH, CURLAUTH_BEARER);
CURLAUTH_BEARER
是在 7.61.0 中添加的。 如果您的 libcurl 较旧,则CURLAUTH_ANY
应该可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.