使用C語言從后臺獲取JSON數據非常常見,在本文中,我們將詳細介紹如何實現這個過程。
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <winsock2.h> #pragma comment(lib, "ws2_32.lib") int main(){ WSADATA wsaData; WSAStartup(MAKEWORD(2, 2), &wsaData); SOCKET clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); SOCKADDR_IN serverAddr; serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(80); serverAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); connect(clientSocket, (SOCKADDR*)&serverAddr, sizeof(serverAddr)); char request[1024]; sprintf(request, "GET /api/json HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: keep-alive\r\nAccept: */*\r\n\r\n"); send(clientSocket, request, strlen(request), 0); char response[2048]; memset(response, 0, sizeof(response)); recv(clientSocket, response, sizeof(response), 0); char* body = strstr(response, "\r\n\r\n") + 4; printf("%s\n", body); closesocket(clientSocket); WSACleanup(); return 0; }
以上代碼實現了從localhost的端口80獲取JSON數據,我們用套接字創(chuàng)建了一個Socket,然后建立與服務器的連接。構造HTTP請求報文后發(fā)送給服務器,再接收服務器的響應,最后從響應中提取JSON數據。