C语言post 和get 方法的实现
我自己实现的post 和get 请求方法,可以直接使用在单片机上,比如ESP32 上,OPl1000 上面,
下面直接上代码。
int client_init(char *ip_add,int prot)
{
int client_fd;
struct sockaddr_in servaddr;
if( (client_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
printf(" socket error !\n");
return -1;
}
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(prot);
if( inet_pton(AF_INET,ip_add, &servaddr.sin_addr) <= 0){
printf(" inet_pton error !\n");
return -1;
}
if( connect(client_fd, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0){
printf(" connect error !\n");
return -1;
}
return client_fd;
}
int http_get_request(int fd,char *path,char *key,char *num)
{
char message[128*2];
sprintf(message, "GET %s?%s=%s HTTP/1.1\r\n",path,key,num);
strcat(message, "Host:自己的网站地址URL\r\n");
strcat(message, "Accept: */*\r\n");
strcat(message, "User-Agent: Mozilla/5.0(compatible)\r\n");
strcat(message, "connection:Keep-Alive\r\n");
strcat(message, "\r\n\r\n");
if(send(fd,message,strlen(message),0)<=0)
{
printf("send data error \n");
return -1;
}
return 0;
}
int http_post_request(int fd,char *macid,char *wifiname,char *name_num,char *wifipwd,char *pwd_num)
{
char message[128*3];
char str[64];
char str_len[8];
sprintf(str,"%s=%s&%s=%s",wifiname,name_num,wifipwd,pwd_num);
sprintf(message, "POST /handle/sendInfo?mac_id=%s HTTP/1.1\r\n",macid);
strcat(message, "Host:自己的网站地址URL\r\n");
strcat(message, "Content-Type: application/x-www-form-urlencoded\r\n");
strcat(message, "Content-Length:");
sprintf(str_len,"%d",strlen(str)+2);
strcat(message,str_len);
strcat(message,"\r\n");
strcat(message, "connection:Keep-Alive\r\n");
strcat(message, "\r\n");
strcat(message,str);
strcat(message,"\r\n");
printf("%s",message);
if(send(fd,message,strlen(message),0)<=0)
{
printf("send data error \n");
return -1;
}
return 0;
}