处理HTTP POST请求/响应

时间:2016-12-10 21:37:10

标签: c++ sockets http unix

我一直试图将HTTP POST请求发送到Facebook但没有成功我从服务器获得此响应:

  

HTTP / 1.1 400错误请求内容类型:text / html; charset = utf-8日期:   2016年12月10日星期六21:28:17 GMT连接:关闭内容长度:2959

Facebook |错误

  

对不起,出了点问题我们正在努力解决它,我们会修复它   我们能够

我的代码

#include <iostream>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>
#include <netdb.h>
#include <fstream>
using namespace std;

int main()
{
    int s, error;
    struct sockaddr_in addr;


        s = socket(AF_INET, SOCK_STREAM, 0);
    if(s <0)
    {
        cout<<"Error 01: creating socket failed!\n";
        close(s);
        return 1;
    }

    addr.sin_family = AF_INET;
    addr.sin_port = htons(80);
    inet_aton("31.13.90.36",&addr.sin_addr);

    error = connect(s,(sockaddr*)&addr,sizeof(addr));
    if(error!=0)
    {
        cout<<"Error 02: conecting to server failed!\n";
        close(s);
        return 1;
    }

     const int msgSize = 1042;
     char msg[] = "POST /login.php?login_attempt=1 \r\n"
                     "HTTP/1.1\r\n"
                     "HOST: facebook.com\r\n\r\n"
                     "Content-type: application/x-www-form-urlencoded\r\n"
                     "Content-Length: 41\r\n"
                     "email=lel@gmail.com&pass=test123&submit=1\r\n" ;







     char answ[1042];

    //cin.getline(&msg[0],256);

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


    ssize_t len;
    while((len = recv(s, msg, strlen(msg), 0)) > 0)
    {
        cout.write(msg, len);

        std::cout << std::flush;
    }
    if(len < 0)
    {
        cout << "error";
    }
    close(s);  

}

我做错了什么?

1 个答案:

答案 0 :(得分:3)

您的讯息中有多处错误。这是您根据代码发送的内容:

1  POST /login.php?login_attempt=1 \r\n
2  HTTP/1.1\r\n 
3  HOST: facebook.com\r\n\r\n
4  Content-type: application/x-www-form-urlencoded\r\n
5  Content-Length: 41\r\n
6  email=lel@gmail.com&pass=test123&submit=1\r\n

相反它应该是这样的:

1  POST /login.php?login_attempt=1 HTTP/1.1\r\n
2  HOST: facebook.com\r\n
3  Content-type: application/x-www-form-urlencoded\r\n
4  Content-Length: 41\r\n
5  \r\n
6  email=lel@gmail.com&pass=test123&submit=1

详细说明:

  • 第1行和第2行应该是一行,即“方法路径HTTP版本”
  • 第3行不应包含多个\r\n
  • 而是空行\r\n应该在所有HTTP标题之后(新行5)
  • 第6行中的正文应仅包含content-length所涵盖的数据。您在那里设置的41个字节不包括您发送的\r\n

除此之外,您没有正确解析响应,而是希望服务器在响应完成后关闭连接。由于您正在使用HTTP/1.1,因此您隐式使用持久连接(HTTP保持活动),因此服务器实际上可能会在同一TCP连接中等待更多请求,而不会立即关闭连接。

我真的建议您研究standard of HTTP,而不是猜测协议可能如何运作。

相关问题