[socket programming] Post data error 411: Length required

hey i'm trying to send a post data with the following code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
int main() {

  try {
    SocketClient s("www.site.com", 80);
    string data = "par1=value1&par2=value2";
    s.SendLine("POST /post_page.php HTTP/1.0\r\n");
    s.SendLine("Host: www.site.com\r\n");
    s.SendLine("User-Agent: Mozilla/4.0\r\n");
    s.SendLine("Content-Length: 23\r\n\r\n");
    s.SendLine("Content-Type: application/x-www-form-urlencoded\r\n");
    s.SendLine("\r\n");
    s.SendLine(data + "\r\n");
    s.SendLine("\r\n");


    while (1) {
      string l = s.ReceiveLine();
      if (l.empty()) break;
      cout << l;
      cout.flush();
    }

  }
  catch (const char* s) {
    cerr << s << endl;
  }
  catch (std::string s) {
    cerr << s << endl;
  }
  catch (...) {
    cerr << "unhandled exception\n";
  }

  return 0;
}


it returns error 411 Length required. I want to make it clear first that the SocketClient class should work properly (I tested it with a GET request) and what it does is evident by the code. I've set the Content-Length as a fixed 23 (by counting data manually) to avoid complicating the problem. So what's the problem?
Thanks,
valleyman
noone can help me??
I'm not familiar with the protocol but are you sure it should be done like this:

s.SendLine("Content-Length: 23\r\n\r\n");

and not like this:

s.SendLine("23\r\n\r\n"); ???

Perhaps the other SendLine calls also need similar modification...

Anyway, google the protocol and see the proper way to communicate with the server. It shouldn't be difficult.

Take a look at this -> http://www.jmarshall.com/easy/http/#postmethod
It first sends Content-Type and then Content-Length (you do it the other way around), I don't know if it's important but I thought I should mention it.
Last edited on
this didn't work at any way, I followed post method specification but nothing...
Thi doesn't look right:

s.SendLine("Content-Length: 23\r\n\r\n");

Only the final header should have a double line end. I think it needs to be:

s.SendLine("Content-Length: 23\r\n");

Otherwise the Content-Type header will be sent as part of the data.
Actually, thinking about it SendLine() probably sends the line breaks itself. So I would try removing all the "\r\n" additions and try this:

1
2
3
4
5
6
7
8
9
    SocketClient s("www.site.com", 80);
    string data = "par1=value1&par2=value2";
    s.SendLine("POST /post_page.php HTTP/1.0");
    s.SendLine("Host: www.site.com");
    s.SendLine("User-Agent: Mozilla/4.0");
    s.SendLine("Content-Length: 23");
    s.SendLine("Content-Type: application/x-www-form-urlencoded");
    s.SendLine(""); // signal end of headers
    s.SendLine(data);
Last edited on
Topic archived. No new replies allowed.