C是一門強大的編程語言,在訪問瀏覽器傳遞的JSON數據方面也非常方便。以下是一個使用C語言訪問其他瀏覽器傳遞JSON數據的示例:
#include <stdio.h> #include <curl/curl.h> #include <jansson.h> int main(int argc, char** argv) { CURL* curl; CURLcode res; char* url = "http://example.com/api/data.json"; char* data = ""; long http_code = 0; curl = curl_easy_init(); if (curl) { curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &http_code); curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS, 2000L); res = curl_easy_perform(curl); if (res != CURLE_OK) { printf("curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); } curl_easy_cleanup(curl); } json_error_t error; json_t* json = json_loads(http_code, JSON_DECODE_ANY, &error); if (json) { printf("HTTP Response Code: %ld\n", http_code); printf("JSON Data: %s\n", json_dumps(json, JSON_INDENT(4))); json_decref(json); } else { printf("JSON Parsing Error: %s\n", error.text); } return 0; } size_t write_callback(void *ptr, size_t size, size_t nmemb, void *userdata) { long* http_code = (long*)userdata; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, http_code); return size * nmemb; }
在這個示例中,我們使用了libcurl庫從遠程URL獲取JSON數據。然后,我們使用jansson庫將數據解析為JSON對象并進行打印。這是一種訪問其他瀏覽器傳遞JSON數據的簡單方法。