use*_*542 8 c++ curl libcurl bearer-token
我正在尝试获取使用 curl.h 库的 C++ 代码来发出需要设置 Authorization: Bearer 标头的 curl 请求。我正在使用 Linux Mint 18 (Ubuntu)。
我已经从命令行发出了这个 curl 请求,它可以工作,它看起来像这样:
curl -H "Content-Type: application/json" -H "Authorization: Bearer <my_token>" <my_url>
Run Code Online (Sandbox Code Playgroud)
这样做会返回一个有效的结果。
但是,我尝试使用 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;
}
Run Code Online (Sandbox Code Playgroud)
我也尝试过使用如下所示的行:
curl_easy_setopt(curl, CURLOPT_XOAUTH2_BEARER, <my_token>);
Run Code Online (Sandbox Code Playgroud)
代替这一行:
curl_slist_append(headers, "Authorization: Bearer <my_token>");
Run Code Online (Sandbox Code Playgroud)
我之前也尝试过添加这些行curl_easy_perform:
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
Run Code Online (Sandbox Code Playgroud)
和
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
Run Code Online (Sandbox Code Playgroud)
因为我在四处搜索时看到了这些线条
但是我所有努力弄清楚如何让这个工作仍然给我留下“错误消息:执行请求的授权不足”。
而且,是的,我顺便确保我使用的 url 和令牌都是正确的。
我做错了什么,如何将顶部的命令行代码正确转换为等效的 C++ 代码。
Ing*_*rdt 11
您需要分配的返回值curl_slist_append(),以 headers在这样的每一个电话:
headers = curl_slist_append(headers, "Content-Type: application/json");
headers = curl_slist_append(headers, "Authorization: Bearer <my_token>");
Run Code Online (Sandbox Code Playgroud)
请参阅此文档
您调用它的方式headers将始终保持为 NULL,这就是您传递给的内容curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
| 归档时间: |
|
| 查看次数: |
6824 次 |
| 最近记录: |