如何使用 libCurl 将访问令牌发送到服务器 API

How to send access token to a server API using libCurl

本文关键字:服务器 API 访问令牌 何使用 libCurl      更新时间:2023-10-16

我已经在一个图片网站注册了,我想使用它的API从那里提取一些图片。
我从他们的文档中引用了以下内容"要获得访问权限,您必须为每个请求添加一个HTTP授权标头"。

目前,我有API_KEY,但我必须通过HTTP授权标头发送它,我发现与我的请求类似的东西如下:

curl -H "授权:OAuth " http://www.example.com

上一个命令在 CURL 命令提示符中使用,但我想要使用 libCurl 做同样的事情。

另外,我知道设置授权类型的选项,但我仍然不知道如何发送ACCESS_TOKEN:

curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);

--

CURL *curl;
CURLcode codeRet;
std::string data;
std::string fullURL = url + keyword;
curl = curl_easy_init();
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, fullURL.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callback);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 60L);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &data);
curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
codeRet = curl_easy_perform(curl);
if (codeRet != CURLE_OK)
// OutputDebugString(wxString(curl_easy_strerror(codeRet)));
return "";
curl_easy_cleanup(curl);
}

如何使用 libCurl 将访问令牌发送到服务器 API?

与命令提示符-H选项一起使用的所有内容curl您可以使用CURLOPT_HTTPHEADER传输到代码。因此,我建议在移动到libcurl之前,确保它一切都按照命令提示符的预期工作。

在访问令牌的情况下,您可以使用access_token关键字,即

curl -H "access_token: abcdefghijklmnopqrstuvwxyz" http://example.com

CURL *curl = curl_easy_init();     
struct curl_slist *headers= NULL;
string token = "abcdefghijklmnopqrstuvwxyz"; // your actual token
if(curl) {
...
curl_easy_setopt(curl, CURLOPT_URL, "http://example.com");
string token_header = "access_token: " + token; // access_token is keyword    
headers = curl_slist_append(headers, token_header.c_tr());     
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
...
curl_slist_free_all(headers);
}

这将向 http://example.com?access_token=abcdefghijklmnopqrstuvwxyz link 发出 http 请求