在C++中,发送POST JSON请求的认证方式主要有以下几种:
示例代码:
#include<iostream>
#include <curl/curl.h>
int main() {
CURL* curl = curl_easy_init();
if (curl) {
// 设置URL
curl_easy_setopt(curl, CURLOPT_URL, "https://example.com/api");
// 设置POST请求
curl_easy_setopt(curl, CURLOPT_POST, 1L);
// 设置JSON数据
std::string json_data = R"({"key": "value"})";
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_data.c_str());
// 设置基本认证
std::string auth = "username:password";
curl_easy_setopt(curl, CURLOPT_USERPWD, auth.c_str());
// 执行请求
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) {
// 设置URL
curl_easy_setopt(curl, CURLOPT_URL, "https://example.com/api");
// 设置POST请求
curl_easy_setopt(curl, CURLOPT_POST, 1L);
// 设置JSON数据
std::string json_data = R"({"key": "value"})";
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_data.c_str());
// 设置令牌认证
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);
// 执行请求
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) {
// 设置URL
curl_easy_setopt(curl, CURLOPT_URL, "https://example.com/api");
// 设置POST请求
curl_easy_setopt(curl, CURLOPT_POST, 1L);
// 设置JSON数据
std::string json_data = R"({"key": "value"})";
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_data.c_str());
// 设置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);
// 执行请求
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++中发送POST JSON请求。选择哪种认证方式取决于你的应用场景和安全需求。