繁体   English   中英

C:POST json 请求使用 sockets 返回 400 错误请求

[英]C: POST json request using sockets returns 400 bad request

我使用请求日志记录从 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"}'

您正在连接到端口 443,这是默认的 HTTPS TLS 端口。 但是您没有协商 TLS 握手以建立加密的 session,然后在该 session 中交换 HTTP 消息。

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

因此,您需要:

  • 连接到端口 80 而不是 443

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM