在C++中,發(fā)送POST JSON請求的認證方式主要有以下幾種:
示例代碼:
#include<iostream>
#include <curl/curl.h>
int main() {
CURL* curl = curl_easy_init();
if (curl) {
// 設(shè)置URL
curl_easy_setopt(curl, CURLOPT_URL, "https://example.com/api");
// 設(shè)置POST請求
curl_easy_setopt(curl, CURLOPT_POST, 1L);
// 設(shè)置JSON數(shù)據(jù)
std::string json_data = R"({"key": "value"})";
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_data.c_str());
// 設(shè)置基本認證
std::string auth = "username:password";
curl_easy_setopt(curl, CURLOPT_USERPWD, auth.c_str());
// 執(zhí)行請求
CURLcode res = curl_easy_perform(curl);
if (res != CURLE_OK) {
std::cerr << "Error: "<< curl_easy_strerror(res)<< std::endl;
}
// 清理
curl_easy_cleanup(curl);
}
return 0;
}
示例代碼:
#include<iostream>
#include <curl/curl.h>
int main() {
CURL* curl = curl_easy_init();
if (curl) {
// 設(shè)置URL
curl_easy_setopt(curl, CURLOPT_URL, "https://example.com/api");
// 設(shè)置POST請求
curl_easy_setopt(curl, CURLOPT_POST, 1L);
// 設(shè)置JSON數(shù)據(jù)
std::string json_data = R"({"key": "value"})";
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_data.c_str());
// 設(shè)置令牌認證
std::string token = "your_token_here";
std::string auth_header = "Bearer " + token;
struct curl_slist* headers = NULL;
headers = curl_slist_append(headers, auth_header.c_str());
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
// 執(zhí)行請求
CURLcode res = curl_easy_perform(curl);
if (res != CURLE_OK) {
std::cerr << "Error: "<< curl_easy_strerror(res)<< std::endl;
}
// 清理
curl_easy_cleanup(curl);
curl_slist_free_all(headers);
}
return 0;
}
示例代碼:
#include<iostream>
#include <curl/curl.h>
int main() {
CURL* curl = curl_easy_init();
if (curl) {
// 設(shè)置URL
curl_easy_setopt(curl, CURLOPT_URL, "https://example.com/api");
// 設(shè)置POST請求
curl_easy_setopt(curl, CURLOPT_POST, 1L);
// 設(shè)置JSON數(shù)據(jù)
std::string json_data = R"({"key": "value"})";
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_data.c_str());
// 設(shè)置API密鑰認證
std::string api_key = "your_api_key_here";
std::string auth_header = "X-API-Key: " + api_key;
struct curl_slist* headers = NULL;
headers = curl_slist_append(headers, auth_header.c_str());
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
// 執(zhí)行請求
CURLcode res = curl_easy_perform(curl);
if (res != CURLE_OK) {
std::cerr << "Error: "<< curl_easy_strerror(res)<< std::endl;
}
// 清理
curl_easy_cleanup(curl);
curl_slist_free_all(headers);
}
return 0;
}
這些認證方式都可以用于C++中發(fā)送POST JSON請求。選擇哪種認證方式取決于你的應(yīng)用場景和安全需求。