gpt4 book ai didi

c - 在 C 中发送 HTTP Post 请求

转载 作者:太空宇宙 更新时间:2023-11-04 02:33:18 26 4
gpt4 key购买 nike

我想在 C 中创建一个 HTTP post 请求。我成功地发送了 Get 方法,但是当我尝试使用 Post 时,程序就停止了。这里的代码:

#include<stdio.h>
#include<winsock2.h>
#include <string.h>

#pragma comment(lib,"ws2_32.lib") //Winsock Library

int main(int argc , char *argv[])
{
WSADATA wsa;
SOCKET s;
struct sockaddr_in server;
char *message , server_reply[2000];
int recv_size;

printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
{
printf("Failed. Error Code : %d",WSAGetLastError());
return 1;
}

printf("Initialised.\n");

//Create a socket
if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
{
printf("Could not create socket : %d" , WSAGetLastError());
}

printf("Socket created.\n");


server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_family = AF_INET;
server.sin_port = htons( 80 );

//Connect to remote server
if (connect(s , (struct sockaddr *)&server , sizeof(server)) < 0)
{
puts("connect error");
return 1;
}

puts("Connected");

// Work well with Get Method
// strcat(message, "GET /voleur/receiver.php?arg1=Hello HTTP/1.1\n");
strcat(message, "POST /voleur/receiver.php HTTP/1.1\n");
strcat(message, "Host: 127.0.0.1\n");
strcat(message, "Connection: close\n");
strcat(message, "Content-Type:application/octet-stream\n");
strcat(message, "Content-Encoding:binary\n");
strcat(message, "Content-Length:16\n");
strcat(message, "Accept-Charset: utf-8\n\n");



if( send(s , message , strlen(message) , 0) < 0)
{
puts("Send failed");
return 1;
}

// My argument
char *data = "arg1=Hello";
send(s , data , strlen(data), 0);
puts("Data Send\n");

//Receive a reply from the server
if((recv_size = recv(s , server_reply , 2000 , 0)) == SOCKET_ERROR)
{
puts("recv failed");
}

puts("Reply received\n");

//Add a NULL terminating character to make it a proper string before printing
server_reply[recv_size] = '\0';
puts(server_reply);

return 0;
}

最佳答案

首先:您应该重新格式化您的 HTTP header :

strcat(message, "Content-Type:application/octet-stream\n");
strcat(message, "Content-Encoding:binary\n");
strcat(message, "Content-Length:16\n");

应该是

strcat(message, "Content-Type: application/octet-stream\n");
strcat(message, "Content-Encoding: binary\n");
strcat(message, "Content-Length: 16\n");

第二个:据我所知,您的问题在于以下几行:

strcat(message, "Content-Length: 16\n");
[...]
char *data = "arg1=Hello";
send(s , data , strlen(data), 0);

因为你声明会有 16 个字节的数据——但你只发送了 10 个字节,这将导致服务器等待剩余的 6 个字节。

关于c - 在 C 中发送 HTTP Post 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40672043/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com