HTTP-获取随机数
从聚合API获取随机数,并解析出随机数
/***************************************************************************
*
* 设计http程序,聚合API发送获取随机数的请求,使用JSON对随机数进行解析
* author:jindouliu2024@163.com
* date:2025.5.22
*
*
*
* Copyright (c) 2024-2025 jindouliu2024@163.com All right Reserved
* *************************************************************************/
#include<stdio.h>
#include<time.h>
#include <unistd.h>
#include<string.h>
#include<errno.h>
#include<stdlib.h>
#include<arpa/inet.h>
#include <unistd.h>
#include<netinet/udp.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include <pthread.h>
#include <netdb.h>
#include"cJSON.h"
#define PORT 80
#define DNS "apis.juhe.cn"
#define KEY " "//自己的秘钥
int main(int argc,char *argv[])
{
char buf[512] = {0};
char rcvbuf[1024] = {0};
char *databuf = calloc(1,4096);
if(databuf == NULL){
printf("calloc error\n");
return 1;
}
char *p = NULL;
int temp = 0;
struct hostent *host;
//创建套接字文件
int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
if(socket_fd == -1){
fprintf(stderr,"socket error errno:%d,%s",errno,strerror(errno));
return 1;
}
host = gethostbyname(DNS);
if(host == NULL){
fprintf(stderr,"gethostbyname error errno:%d,%s",errno,strerror(errno));
return 2;
}
//绑定服务器的端口和地址
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_port = htons(PORT);
server.sin_addr.s_addr = ((struct in_addr *)(host->h_addr_list[0]))->s_addr;
//申请连接
int flag = connect(socket_fd,(struct sockaddr *)&server,sizeof(server));
if(flag == -1){
fprintf(stderr,"connect error errno:%d,%s",errno,strerror(errno));
return 1;
}
//HTTP协议格式
sprintf(buf,"GET http://apis.juhe.cn/fapig/pwdgenerator/generate?key=%s&len=4&t=3 "
"HTTP/1.1\r\n"
"Host:apis.juhe.cn\r\n"
"Connection: close\r\n"
"Content-Type:application/x-www-form-urlencoded\r\n"
"\r\n",KEY);
//双方建立连接
send(socket_fd,buf,strlen(buf),0);
int bytes = 0;
//接收数据
while((bytes =recv(socket_fd, rcvbuf, sizeof(rcvbuf) - 1, 0)) > 0){
strcat(databuf,rcvbuf);
bzero(rcvbuf,sizeof(rcvbuf));
}
char *newptr = strstr(databuf,"{");
// 解析JSON数据
cJSON *json = cJSON_Parse(newptr);
printf("Parsed JSON:\n%s\n", cJSON_Print(json));
cJSON *result = cJSON_GetObjectItem(json,"result");
cJSON *content = cJSON_GetObjectItem(result,"content");
printf("%s\n",content->valuestring);
return 0;
}
浙公网安备 33010602011771号