c++ http client post json

在 C++ 中,可以使用第三方库来发送 HTTP POST 请求并附加 JSON 数据。这里我们介绍一个常用的开源库:cURL。

使用 cURL 发送 HTTP POST 请求附加 JSON 数据的步骤如下:

安装 cURL 库。

在代码中引入 cURL 头文件。

#include <curl/curl.h>

初始化 cURL。

CURL *curl;
curl = curl_easy_init();

设置请求的 URL。

curl_easy_setopt(curl, CURLOPT_URL, "http://example.com/api");

设置请求方法为 POST。

curl_easy_setopt(curl, CURLOPT_POST, 1L);

设置请求头。

struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "Content-Type: application/json");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

设置请求体,即 JSON 数据。

const char *json_data = "{\"name\": \"John\", \"age\": 30}";
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_data);

执行请求。

CURLcode res;
res = curl_easy_perform(curl);

检查请求是否成功。

if (res != CURLE_OK) {
  fprintf(stderr, "curl_easy_perform() failed: %s\n",
          curl_easy_strerror(res));

释放资源。

curl_slist_free_all(headers);
curl_easy_cleanup(curl);

下面是完整的代码示例:

#include <curl/curl.h>
#include <stdio.h>
int main(void) {
  CURL *curl;
  CURLcode res;
  struct curl_slist *headers = NULL;
  curl = curl_easy_init();
  if (curl) {
    curl_easy_setopt(curl, CURLOPT_URL, "http://example.com/api");
    curl_easy_setopt(curl, CURLOPT_POST, 1L);
    headers = curl_slist_append(headers, "Content-Type: application/json");
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    const char *json_data = "{\"name\": \"John\", \"age\": 30}";
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_data);
    res = curl_easy_perform(curl);
    if (res != CURLE_OK) {
      fprintf(stderr, "curl_easy_perform() failed: %s\n",
              curl_easy_strerror(res));
    curl_slist_free_all(headers);
    curl_easy_cleanup(curl);
  return 0;

这个示例中发送的 JSON 数据为 {"name": "John", "age": 30},可以根据需要修改。在实际使用中,还需要处理请求的响应数据。

  •