下面我們來看一下如何使用c語言發送json http請求。
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <curl/curl.h> static size_t write_callback(char *data, size_t size, size_t nmemb, void *userdata) { printf("%s", data); return size * nmemb; } int main() { CURL *curl; CURLcode res; curl = curl_easy_init(); if (curl) { const char *url = "https://jsonplaceholder.typicode.com/posts"; const char *json_data = "{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}"; struct curl_slist *headers = NULL; headers = curl_slist_append(headers, "Content-Type: application/json"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_data); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback); res = curl_easy_perform(curl); if (res != CURLE_OK) { printf("curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); } curl_easy_cleanup(curl); } return EXIT_SUCCESS; }
上述代碼中,我們使用了curl庫來發送http請求。首先我們初始化了一個curl對象,然后設置了請求url和請求體(json格式)。接著我們設置請求頭部,其中Content-Type為application/json。最后我們設置了回調函數來接收響應結果并打印輸出。
上一篇python 維持會話
下一篇c 反射json