温馨提示×

c++ post请求怎样添加头部

c++
小樊
108
2024-07-15 23:39:44
栏目: 编程语言

在C++中进行POST请求时,可以使用HTTP头部来添加请求头。以下是一个基本的示例代码:

#include <iostream>
#include <curl/curl.h>

int main() {
    CURL *curl;
    CURLcode res;

    curl = curl_easy_init();
    if (curl) {
        curl_easy_setopt(curl, CURLOPT_URL, "http://example.com"); // 设置请求的URL
        curl_easy_setopt(curl, CURLOPT_POST, 1); // 设置请求为POST请求

        struct curl_slist *headers = NULL;
        headers = curl_slist_append(headers, "Content-Type: application/json"); // 添加Content-Type头部
        headers = curl_slist_append(headers, "Authorization: Bearer ABC123"); // 添加Authorization头部
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); // 设置请求头部

        res = curl_easy_perform(curl);
        if (res != CURLE_OK) {
            std::cerr << "Error: " << curl_easy_strerror(res) << std::endl;
        }

        curl_slist_free_all(headers); // 释放内存
        curl_easy_cleanup(curl);
    }

    return 0;
}

在上面的示例中,我们使用了libcurl库来发起HTTP请求,并通过curl_slist_append函数向请求中添加了Content-Type和Authorization的头部信息。最后,我们通过curl_easy_setopt函数将这些头部信息添加到请求中。

0