C:使用套接字的 POST json 请求返回 400 错误请求

时间:2021-04-10 20:50:27

标签: c sockets

我使用请求日志记录从 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 的请求模块中得到的请求:

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"}'

1 个答案:

答案 0 :(得分:0)

您正在连接到端口 443,这是默认的 HTTPS TLS 端口。但是,在该会话内交换 HTTP 消息之前,您并没有协商 TLS 握手来建立加密会话。

服务器在需要加密的端口上检测到未加密的 HTTP 消息,因此它发送回未加密的响应,并可能终止连接。

因此,您需要:

  • 连接到端口 80 而不是 443

  • 正确实施 TLS,例如使用 OpenSSL 或任何其他类似的加密库/API。