在C中发送HTTP发布请求

时间:2016-11-18 08:02:10

标签: c apache http-post

我想在C中创建一个HTTP post请求。我已成功发送Get Method但是,当我尝试使用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;
}  

1 个答案:

答案 0 :(得分:1)

第一: 您应该重新格式化HTTP标头:

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个字节。