在C中實(shí)現(xiàn)帶有JSON的GET請(qǐng)求需要使用如下流程:
1. 導(dǎo)入必要的頭文件
2. 創(chuàng)建一個(gè)HTTP請(qǐng)求
3. 設(shè)置請(qǐng)求方法為GET
4. 設(shè)置請(qǐng)求的URL
5. 設(shè)置請(qǐng)求頭
6. 使用libcurl發(fā)送請(qǐng)求
7. 處理響應(yīng)
8. 解析JSON數(shù)據(jù)
具體代碼實(shí)現(xiàn)如下:
#include <stdio.h>
#include <stdlib.h>
#include <curl/curl.h>
#include <jansson.h>
int main(void) {
CURL *curl;
CURLcode res;
json_error_t error;
json_t *root;
const char* url = "https://jsonplaceholder.typicode.com/posts/1";
curl_global_init(CURL_GLOBAL_DEFAULT);
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L);
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "Content-Type: application/json");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
res = curl_easy_perform(curl);
if(res == CURLE_OK) {
long response_code;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
printf("Response code: %ld\n", response_code);
char *data;
int data_size;
curl_easy_getinfo(curl, CURLINFO_SIZE_DOWNLOAD, &data_size);
data = (char*)malloc(data_size);
curl_easy_getinfo(curl, CURLINFO_CONTENT_TYPE, &data);
printf("Content-type: %s\n", data);
root = json_loads(data, 0, &error);
if (!root) {
fprintf(stderr, "error: on line %d: %s\n", error.line, error.text);
return 1;
}
json_t *userId;
json_t *id;
json_t *title;
json_t *body;
json_unpack(root, "{s:o, s:o, s:o, s:o}", "userId", &userId, "id", &id, "title", &title, "body", &body);
printf("userId: %d, id: %d\n", json_integer_value(userId), json_integer_value(id));
printf("title: %s\n", json_string_value(title));
printf("body: %s\n", json_string_value(body));
json_decref(userId);
json_decref(id);
json_decref(title);
json_decref(body);
} else {
printf("Error: %s\n", curl_easy_strerror(res));
}
curl_easy_cleanup(curl);
}
curl_global_cleanup();
return 0;
}
以上代碼可以正常發(fā)送GET請(qǐng)求并解析JSON數(shù)據(jù),可以根據(jù)需要進(jìn)行修改。