利用cJSON库解析http返回参数

利用cJSON库解析http返回参数

在C语言中,使用cJSON库来解析HTTP响应返回的JSON参数通常涉及几个步骤:

  1. 发送HTTP请求(可以利用soket库进行http请求)
  2. 接收HTTP响应的数据
  3. 将接收到的数据作为字符串传递给cJSON库进行解析
  4. 使用cJSON API访问和提取JSON数据

以下是一个示例,展示了如何使用soket向特定的API接口发送HTTP GET请求,并使用cJSON解析返回的JSON数据:

首先,确保你已经安装了socket和cJSON库

/*******************************************************************
*
*	file name:	get_tenphone.c
*	author	 :  m17872844806@163.com
*	date	 :  2024/06/11
*	function :  利用socket库对API接口发送http请求,并解析返回的参数
* 	note	 :  None
*
*	CopyRight (c)  2023-2024   m17872844806@163.com  All Right Reseverd 
*
* *****************************************************************/
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <errno.h>
#include <string.h>
#include "cJSON.h"

#define APIKEY  "******************"//以两宏定义参数替换成自己的参数
#define PHONE   "*************"	 
int main(int argc, char const *argv[])
{
	
	int tcp_socket = socket(AF_INET, SOCK_STREAM, 0);

	
	struct sockaddr_in  destaddr;
	destaddr.sin_family = AF_INET; 
	destaddr.sin_port   = htons(80); 
	destaddr.sin_addr.s_addr = inet_addr("203.107.54.210"); 
	
	int ret = connect(tcp_socket,(struct sockaddr *)&destaddr, sizeof(destaddr));
	if (-1 == ret)
	{
		perror("connect server error");
		exit(1);
	}

	printf("connect success!\n");

	 char recvbuf[1024] ={0};
	 sprintf(recvbuf, "GET http://apis.juhe.cn/mobile/get?phone=%s&key=%s HTTP/1.1\r\n"
                     "Host:apis.juhe.cn\r\n"
                    "Content-Type: application/x-www-form-urlencoded\r\n"
	 			            "\r\n\r\n"
                 ,PHONE,APIKEY);


	
  send(tcp_socket,recvbuf,strlen(recvbuf),0);
 
	char *deal;
	while(1)
	{
		recv(tcp_socket,recvbuf,1024,0);  
		printf("%s\n",recvbuf);

		deal=strstr(recvbuf,"{");
	    printf("%s\n",deal);
		
		break;
	}
     
	cJSON *root = cJSON_Parse(deal);
	printf("%s\n",cJSON_Print(root)); 

	cJSON * obj1 = cJSON_GetObjectItem(root,"result");
	
	 cJSON *province = cJSON_GetObjectItem(obj1,"province");
	 printf("地区:%s",province->valuestring);
	
	cJSON *city = cJSON_GetObjectItem(obj1,"city");
	 printf("%s\n",city->valuestring);

	cJSON *company = cJSON_GetObjectItem(obj1,"company");
	 printf("运营商:%s\n",company->valuestring); 

	return 0;
}

如果代码用法有什么问题,请将问题发至网易邮箱 m17872844806@163.com,作者将及时改正,欢迎与各位老爷交流讨论。

麻烦三连加关注!!!!

比心

posted @ 2024-06-12 18:58  琨为玉也  阅读(5)  评论(0编辑  收藏  举报