c语言实现根据http提供的Content-Length提取消息体信息
时间: 2023-08-10 16:03:10 浏览: 57
可以使用C语言中的socket库来进行HTTP通信,并通过解析HTTP响应头中的Content-Length字段来获取消息体的长度,然后从socket中读取相应长度的数据即可。
以下是一个示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netdb.h>
#define MAX_BUF_SIZE 1024
int main(int argc, char *argv[])
{
if (argc != 2) {
printf("Usage: %s <url>\n", argv[0]);
return 1;
}
char *url = argv[1];
// 解析URL
struct hostent *server = gethostbyname(url);
if (server == NULL) {
printf("Error: cannot resolve hostname %s\n", url);
return 1;
}
struct sockaddr_in server_addr = {0};
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(80);
server_addr.sin_addr = *((struct in_addr *) server->h_addr);
// 创建socket
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
printf("Error: cannot open socket\n");
return 1;
}
// 连接服务器
if (connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
printf("Error: cannot connect to server\n");
return 1;
}
// 发送HTTP请求
char request[MAX_BUF_SIZE] = {0};
snprintf(request, MAX_BUF_SIZE, "GET / HTTP/1.1\r\nHost: %s\r\n\r\n", url);
int n = write(sockfd, request, strlen(request));
if (n < 0) {
printf("Error: cannot send request\n");
return 1;
}
// 解析HTTP响应头
char response[MAX_BUF_SIZE] = {0};
n = read(sockfd, response, MAX_BUF_SIZE);
if (n < 0) {
printf("Error: cannot receive response\n");
return 1;
}
char *body_start = strstr(response, "\r\n\r\n") + 4;
int body_len = atoi(strstr(response, "Content-Length: ") + strlen("Content-Length: "));
char *body_end = body_start + body_len;
// 读取消息体
char body[MAX_BUF_SIZE] = {0};
memcpy(body, body_start, body_len);
while (body_end > body_start) {
n = read(sockfd, body + body_len - (body_end - body_start), body_end - body_start);
if (n < 0) {
printf("Error: cannot receive body\n");
return 1;
}
body_end -= n;
}
printf("Response body: %s\n", body);
close(sockfd);
return 0;
}
```
注意,以上代码仅供参考,并未进行错误处理和完整性校验,请勿直接用于生产环境。