-2

我尝试使用 Code::Blocks .c 发送 HTTP POST 请求,但我不知道消息有什么问题,我在谷歌中搜索,所有教程都教我像我一样做,所以如果有人可以帮助我,我会感谢你,这是我对网站的要求::

    sprintf(buffer, "POST /index.php HTTP/1.1\r\nContent-Lenght: %d\r\n", 7+strlen(action)+3+strlen(id));
strcat(buffer, "Host: www.testserv.com \r\n\r\n");
strcat(buffer, "action=");strcat(buffer, action);
strcat(buffer, "&");
strcat(buffer, "id=");strcat(buffer, id);

printf("Requisicao:\n%s\n\n", buffer);

send(s, buffer, strlen(buffer), 0);

这个请求似乎是正确的,但她没有做错什么?

----EDITED--- 问题是:我的post请求不起作用,服务器只解释HTTP标头,但表单itens的值没有!

解释站点:该站点有一个 index.php 页面和一个由 index.php 调用的第二个页面:send.php。索引页面有一个带有 3 个元素的表单:2 个文本框(操作和 id)和一个提交按钮,我在 2 个文本框(用于测试)上写了任何东西,当我按下提交时,通过 POST 方法的表单将调用发送.php 页面,此页面将向我们展示我在 2 个文本框中写的内容,我将向您展示的功能是用于连接服务器,并使用 POST 方法请求 send.php 并尝试为服务器传递文本框变量的值。

这是完整的功能:

int enviar(const char* action, const char* id){

#define ACTION "action="
#define ID "&id="

char head[500], buff_msg[500];
int s, len;
struct sockaddr_in inf;

if((s=socket(AF_INET, SOCK_STREAM, 0)) == -1)
    return -1;

inf.sin_family = AF_INET;
inf.sin_port = htons(80);
inf.sin_addr.s_addr = inet_addr("10.1.10.1");
memset(inf.sin_zero, 0, 8);

if(connect(s, (struct sockaddr*)&inf, sizeof(inf)) == -1)
    return -1;

memset(head, 0, 500);
memset(buff_msg, 0, 500);

sprintf(head, "POST /page_called_by_the_index.php / HTTP/1.1\r\nContent-Length: %d\r\n",
                                                    strlen(ACTION)+strlen(action)
                                                   +strlen(ID)+strlen(id));
strcat(head, "host: the_server.com\r\n\r\n");
strcat(head, ACTION);
strcat(head, action);
strcat(head, ID);
strcat(head, id);

printf("Header HTTP[%d]:\n%s\n", strlen(cab), cab);

len = send(s,head, strlen(cab), 0);

if(len <= 0){
    perror("send");
    return 0;
}

printf("%d bytes have been sent\n", len);

while((len=recv(s, buff_msg, 500, 0)) > 0){
    printf("%d bytes read:\n%s\n", len, buff_msg);
    memset(buff_msg, 0, 500);
}

return 1;}

标头请求很好,因为服务器给我发回了 200 OK,但是这些值没有被解释!

我感谢你的帮助。

4

1 回答 1

4

您的 POST 命令中有几个错误

Content-Lenght

应该

Content-Length

7+strlen(action)+3+strlen(id)

假设 3 for 是一个字符太短&id=(这需要 4 个字符,因此您的内容长度将省略您的 id 的最后一个字符)。如果您对当前正在硬编码其长度的字符串使用变量(或定义)会更安全

#define ACTION "action="
#define ID "&id="

sprintf(buffer, "POST /index.php HTTP/1.1\r\nContent-Length: %d\r\n",
                sizeof(ACTION)-1+strlen(action)+sizeof(ID)-1+strlen(id));
strcat(buffer, "Host: www.testserv.com \r\n\r\n");
strcat(buffer, ACTION);
strcat(buffer, action);
strcat(buffer, ID);
strcat(buffer, id);
于 2013-07-02T13:59:05.340 回答