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

How to send access token to a server API using libCurl

我已经注册了一个图片网站,我想用它 API 从那里拉一些图片。
我从他们的文档 "To get access you have to add an HTTP Authorization header to each of your requests " 中引用了以下内容。

目前,我有 API_KEY,但我必须通过 HTTP 授权 header 发送它,我发现与我的请求类似的内容如下:

curl -H "Authorization: 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?

curl 命令提示符下与 -H 选项一起工作的所有内容都可以使用 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 请求