http与cJSON练习

news/2024/10/5 3:21:02

http与cJSON练习

/****************************************************************************************************
*                                       weather_test.c
*               练习tcp连接,与http协议,调用服务器接口,实现获取特定城市的天气信息,并用cJSON解析
*               需要添加cJSON.c和cJSON.h
*               下载地址https://github.com/DaveGamble/cJSON
****************************************************************************************************/
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/udp.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdbool.h>
#include <netdb.h>#include "cJSON.h"#define PORT 80                                //http协议默认80端口
#define DOMAIN_NAME "api.seniverse.com"            //天气接口API,此处使用的是心知天气
#define CITY        "Jieyang"                      //城市
#define KEY      "S23Bdt3KcyGvyz3kb"            //密钥//套接字
int tcp_socket = 0;//接收缓冲区
char recv_buf[1024] = {0};/***函数名称	connect_init*函数功能	初始化tcp连接*函数参数	NONE*返回结果	布尔型*注意事项	NONE*/
bool connect_init()
{  //创建TCP套接字tcp_socket = socket(AF_INET, SOCK_STREAM, 0);if (tcp_socket == -1){fprintf(stderr, "tcp socket error,errno:%d,%s\n",errno,strerror(errno));return false;}/*****************************相关结构体*******************************///  struct hostent {//        char  *h_name;            /* official name of host *///        char **h_aliases;         /* alias list *///        int    h_addrtype;        /* host address type *///        int    h_length;          /* length of address *///        char **h_addr_list;       /* list of addresses *///    }/********************************************************************///解析域名struct hostent* ipaddr=gethostbyname(DOMAIN_NAME);struct in_addr *addr = (struct in_addr *)ipaddr->h_addr_list[0];printf("%s\n", inet_ntoa(*addr));//初始化结构体struct sockaddr_in weather_addr;//协议weather_addr.sin_family         = AF_INET;//端口weather_addr.sin_port          = htons(PORT);//服务器地址weather_addr.sin_addr. s_addr   = inet_addr(    inet_ntoa(*addr)    );//开始连接int ret = connect(tcp_socket,(struct sockaddr*)&weather_addr,sizeof(weather_addr));if(-1 == ret){fprintf(stderr, "connect error,errno:%d,%s\n",errno,strerror(errno));return false;}printf("连接成功\n");return true;
}/***函数名称	request_http*函数功能	http请求*函数参数	NONE*返回结果	NONE*注意事项	NONE*/
void request_http()
{//请求缓冲区char req_buf[1024] = {0};//向缓冲区写入请求sprintf(req_buf,"GET https://api.seniverse.com/v3/weather/now.json?key=%s&location=%s&language=zh-Hans&unit=c "  //空格不能省略"HTTP/1.1""\r\n""HOST:%s\r\n""\r\n",KEY,CITY,DOMAIN_NAME);//循环请求直到成功接收信息while(1){//发送请求if( -1 == send(tcp_socket,req_buf,sizeof(req_buf),0) ){fprintf(stderr,"send error,errno[%d]:%s\n",errno,strerror(errno));continue;}printf("请求发送成功\n");//第一次接收响应if( -1 == recv(tcp_socket,recv_buf,sizeof(recv_buf),0)  ){fprintf(stderr,"recv error,errno[%d]:%s\n",errno,strerror(errno));continue;}printf("%s\n",recv_buf);//清零bzero(recv_buf,1024);printf("*******************************************\n");//第二次接收响应if(-1 == recv(tcp_socket,recv_buf,sizeof(recv_buf),0)){fprintf(stderr,"recv error,errno[%d]:%s\n",errno,strerror(errno));continue;}//此处不可清零,需要解析JSONprintf("%s\n",recv_buf);break;}}/***函数名称	weather_JSON*函数功能	解析JSON*函数参数	NONE*返回结果	NONE*注意事项	NONE*/
void weather_JSON()
{//将字符串转换为josn格式cJSON* weather = cJSON_Parse(recv_buf);//解析cJSON* results  = cJSON_GetObjectItem(weather, "results");cJSON* array    = cJSON_GetArrayItem(results,0);cJSON* location = cJSON_GetObjectItem(array,"location");cJSON* name     = cJSON_GetObjectItem(location,"name");cJSON* country  = cJSON_GetObjectItem(location,"country");cJSON* now      = cJSON_GetObjectItem(array,"now");cJSON* text     = cJSON_GetObjectItem(now,"text");cJSON* last_update = cJSON_GetObjectItem(array,"last_update");/*****************************相关结构体*******************************/// typedef struct cJSON {//     struct cJSON *next,*prev;	//     struct cJSON *child;		//     int type;					//     char *valuestring;			//     int valueint;				//     double valuedouble;			//     char *string;				// } cJSON;/********************************************************************/printf("当前城市%s-%s,该城市天气为%s   %s\n",   country->valuestring,name->valuestring,text->valuestring,last_update->valuestring);}int main()
{connect_init();request_http();weather_JSON();return 0;
}

运行结果
image

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hjln.cn/news/44249.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈,一经查实,立即删除!

相关文章

多线程实现并发

多线程实现并发案例多线程并发服务器 架构 void* thread_fun(void* arg) {while(1){recv()/send()} }scokfd = socket() bind() listen() while(1){accept()//连上就创建线程pthread_create(, ,thread_fun, )pthread_detach() }案例 /* # Multi-process concurrent server…

IO多路复用

高性能并发IO多路复用详解IO多路复用什么是IO多用复路 IO多路复用(Input/Output Multiplexing)是一种在单个线程中管理多个输入/输出通道的技术。它允许一个线程同时监听多个输入流(例如网络套接字、文件描述符等),并在有数据可读或可写时进行相应的处理,而不需要为每个通…

利用聚合API平台的API接口,利用HTTP协议向服务器发送请求,并接受服务器的响应,要求利用cJSON库对服务器的响应数据进行解析,并输出到终端

目录题目分析代码结果 题目利用聚合API平台的API接口,利用HTTP协议向服务器发送请求,并接受服务器的响应,要求利用cJSON库对服务器的响应数据进行解析,并输出到终端 分析1.需从源代码网站GitHub或SourceForge代码网站下载cJSON库及阅读下载的README相关手册如何使用cJSON库…

[DP] [倍增优化] Luogu P1081 [NOIP2012 提高组] 开车旅行

[NOIP2012 提高组] 开车旅行 题目描述 小 \(\text{A}\) 和小 \(\text{B}\) 决定利用假期外出旅行,他们将想去的城市从 $1 $ 到 \(n\) 编号,且编号较小的城市在编号较大的城市的西边,已知各个城市的海拔高度互不相同,记城市 \(i\) 的海拔高度为\(h_i\),城市 \(i\) 和城市 \…

【esp32 学习笔记】让SD卡发光发热~

原理图:图 SD卡部分图 MCU中与SD卡相关的接口 连接关系如下:[ESP32 IO26 – CS MICROSD] [ESP32 IO23 – MOSI(DI) MICROSD] [ESP32 IO19 – MISO(DO) MICROSD] [ESP32 IO18 – SCK MICROSD] [ESP32 GND – GND MICROSD] [3.3V – VCC MICROSD] 软件: 我们将使用SD卡库…

网络编程练习题---利用cJSON库对服务器返回的JSON格式数据完成解析

利用HTTP协议向聚合数据API发送请求,并利用cJSON库对服务器返回的JSON格式数据完成解析目录题目注意事项实现代码结果展示相关接口指引 题目利用某些平台(聚合API、百度AI、科大讯飞API)的API接口,利用HTTP协议向服务器发送请求,并接受服务器的响应,要求利用cJSON库对服务…

嵌入式Linux中的LED驱动控制(续)

前面的实例实现了在野火STM32MP157开发板上对三个LED灯的控制,这里来讨论一下该驱动程序的具体实现方式。由于实例使用的是STM32MP157这款芯片,所以先来看一下与该芯片端口操作相关的寄存器。 先看端口模式寄存器MODER,该类型的寄存器在STM32MP157中有11个,即x的值从A到K。…

通讯协议转换Modbus转Profinet网关

Modbus转Profinet网关是工业通信转换设备,能够实现Modbus协议与Profinet协议之间的有效转换和稳定传输。通过该网关,工业设备之间可以实现数据交换和通信,提高生产效率和智能化程度。支持Modbus RTU主从站。此外,Modbus转 Profinet网关自带网络和串口,支持485/232接口Modb…