http client C++代码
时间: 2023-10-09 10:15:24 浏览: 57
以下是一个简单的使用C语言编写的HTTP客户端代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#define BUFFER_SIZE 1024
int main(int argc, char *argv[]) {
int sockfd;
struct sockaddr_in servaddr;
char buffer[BUFFER_SIZE];
char *host = "www.example.com";
char *page = "/";
int port = 80;
// 创建socket
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
printf("Error: Could not create socket\n");
return 1;
}
// 获取服务器IP地址
struct hostent *server = gethostbyname(host);
if (server == NULL) {
printf("Error: Could not resolve host\n");
return 1;
}
// 设置socket地址
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(port);
memcpy(&servaddr.sin_addr.s_addr, server->h_addr, server->h_length);
// 连接服务器
if (connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) {
printf("Error: Could not connect to server\n");
return 1;
}
// 构造HTTP请求
sprintf(buffer, "GET %s HTTP/1.1\r\n", page);
sprintf(buffer+strlen(buffer), "Host: %s\r\n", host);
sprintf(buffer+strlen(buffer), "Connection: close\r\n");
sprintf(buffer+strlen(buffer), "\r\n");
// 发送HTTP请求
if (send(sockfd, buffer, strlen(buffer), 0) < 0) {
printf("Error: Could not send request\n");
return 1;
}
// 接收响应并输出
int n = 0;
while ((n = recv(sockfd, buffer, BUFFER_SIZE-1, 0)) > 0) {
buffer[n] = '\0';
printf("%s", buffer);
}
// 关闭socket
close(sockfd);
return 0;
}
```
该代码通过socket连接到指定的服务器,构造HTTP请求并发送,然后接收服务器的响应并输出。需要注意的是,该代码只能处理简单的HTTP请求,对于复杂的HTTP请求,需要使用更为复杂的代码来处理。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)