#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <time.h>
#include <errno.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <arpa/inet.h>
char* httpGet(const char* IPSTR, int PORT){
int sockfd, ret, i, h;
struct sockaddr_in servaddr;
char str1[4096], str2[4096], *str;
char* buf = (char*)malloc(4096);
socklen_t len;
fd_set t_set1;
struct timeval tv;
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) {
printf("socket error!\n");
free(buf);
return 0;
};
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
printf("IP: %s, PORT %d\n", IPSTR, PORT);
servaddr.sin_port = htons(PORT);
if (inet_pton(AF_INET, IPSTR, &servaddr.sin_addr) <= 0 ){
printf("inet_pton error!\n");
free(buf);
return 0;
};
if (connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0){
printf("connect error!\n");
free(buf);
return 0;
}
memset(str2, 0, 4096);
strcat(str2, "theDataToPost");
str=(char *)malloc(128);
len = strlen(str2);
sprintf(str, "%d", len);
memset(str1, 0, 4096);
strcat(str1, "GET / HTTP/1.1\n");
strcat(str1, "Host: ");
strcat(str1, IPSTR);
strcat(str1, "\n");
strcat(str1, "Content-Type: text/html\n");
strcat(str1, "Content-Length: ");
strcat(str1, str);
strcat(str1, "\n\n");
strcat(str1, str2);
strcat(str1, "\r\n\r\n");
printf("%s\n",str1);
ret = write(sockfd,str1,strlen(str1));
if (ret < 0) {
printf("Error code %d,error message '%s'\n",errno, strerror(errno));
free(buf);
return 0;
}else{
printf("Send successful,send %d bytes!\n\n", ret);
}
FD_ZERO(&t_set1);
FD_SET(sockfd, &t_set1);
sleep(2);
tv.tv_sec= 0;
tv.tv_usec= 0;
h= 0;
printf("--------------->1");
h= select(sockfd +1, &t_set1, NULL, NULL, &tv);
printf("--------------->2 %d\n", h);
//if (h == 0) continue;
if (h < 0) {
close(sockfd);
printf("SELECT ERROR,Thread terminate!\n");
free(buf);
return 0;
};
if (h > 0){
memset(buf, 0, 4096);
i= read(sockfd, buf, 4095);
if (i==0){
close(sockfd);
printf("Server close, Thread terminate!\n");
free(buf);
return 0;
}
}
close(sockfd);
return buf;
}
int main()
{
char* s = httpGet("127.0.0.1", 8080);
printf("out:%s\n", s);
return 0;
}
c++实现HTTP的get请求
最新推荐文章于 2025-03-22 10:51:41 发布