【发布时间】:2021-04-10 20:50:27
【问题描述】:
我使用请求日志从 Python 获得原始请求,其中状态为 200:
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main(void) {
struct addrinfo hints, *res;
int sockfd;
char buf[2056];
int byte_count;
memset(&hints, 0,sizeof hints);
hints.ai_family=AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
getaddrinfo("example.com","443", &hints, &res);
sockfd = socket(res->ai_family,res->ai_socktype,res->ai_protocol);
printf("Connecting...\n");
connect(sockfd,res->ai_addr,res->ai_addrlen);
printf("Connected!\n");
char *header = "POST /abc HTTP/1.1\r\nHost: example.com\r\nAccept-Encoding: gzip, deflate\r\nAccept: application/json\r\nConnection: keep-alive\r\nContent-Type: application/json\r\nContent-Length: 22\r\n\r\n{\"abcdeghiewf\": \"abc\"}";
send(sockfd,header,strlen(header),0);
printf("POST Sent...\n");
byte_count = recv(sockfd,buf,sizeof(buf),0);
printf("recv()'d %d bytes of data in buf\n",byte_count);
printf("%.*s",byte_count,buf);
return 0;
}
这是我从 Python 的 requests 模块收到的请求:
send: b'POST /abc HTTP/1.1\r\nHost: example.com\r\nAccept-Encoding: gzip, deflate\r\nAccept: application/json\r\nConnection: keep-alive\r\nContent-Type: application/json\r\nContent-Length: 22\r\n\r\n'
send: b'{"abcdeghiewf": "abc"}'
【问题讨论】:
-
附带说明,此代码中没有任何错误处理。你调用的任何函数都可能失败,你没有检查。