C語言作為一種底層編程語言,可以操作底層資源,包含網絡資源。下面我們來介紹如何利用C語言訪問網站獲取JSON。
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <curl/curl.h> struct MemoryStruct { char *memory; size_t size; }; static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) { size_t realsize = size * nmemb; struct MemoryStruct *mem = (struct MemoryStruct *) userp; mem->memory = realloc(mem->memory, mem->size + realsize + 1); if(mem->memory == NULL) { printf("out of memory\n"); exit(EXIT_FAILURE); } memcpy(&(mem->memory[mem->size]), contents, realsize); mem->size += realsize; mem->memory[mem->size] = '\0'; return realsize; } int main(void) { CURL *curl_handle; CURLcode res; struct MemoryStruct chunk; chunk.memory = malloc(1); chunk.size = 0; curl_global_init(CURL_GLOBAL_ALL); curl_handle = curl_easy_init(); curl_easy_setopt(curl_handle, CURLOPT_URL, "https://api.github.com/"); curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&chunk); curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "libcurl-agent/1.0"); res = curl_easy_perform(curl_handle); if(res != CURLE_OK) { fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); } else { printf("%lu bytes retrieved\n", (unsigned long) chunk.size); printf("%s\n", chunk.memory); } curl_easy_cleanup(curl_handle); free(chunk.memory); curl_global_cleanup(); return 0; }
以上為使用CURL庫實現訪問網站獲取JSON的代碼,主要是通過函數writeback將獲取到的JSON存到chunk.memory中,使用printf打印獲取到的JSON內容。