curl authorization header
To add an authorization header in a curl request using C, you can use the curl_easy_setopt
function with the CURLOPT_HTTPHEADER
option. Here's an example:
#include <stdio.h>
#include <curl/curl.h>
int main(void) {
CURL *curl;
CURLcode res;
curl_global_init(CURL_GLOBAL_DEFAULT);
curl = curl_easy_init();
if(curl) {
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "Authorization: Bearer your_token_here");
curl_easy_setopt(curl, CURLOPT_URL, "https://example.com/api");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
res = curl_easy_perform(curl);
if(res != CURLE_OK)
fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
curl_easy_cleanup(curl);
}
curl_global_cleanup();
return 0;
}
In the above code, we first initialize the curl library using curl_global_init
. Then, we create a curl handle using curl_easy_init
. We create a struct curl_slist
variable called headers
to hold the headers we want to add to the request. We add the authorization header using curl_slist_append
. Next, we set the URL for the request using curl_easy_setopt
with CURLOPT_URL
. Finally, we set the headers using curl_easy_setopt
with CURLOPT_HTTPHEADER
. After performing the request using curl_easy_perform
, we clean up the resources using curl_easy_cleanup
and curl_global_cleanup
.