c++httpboostboost-asio

C++ Http POST 400 bad request


The following code was able to perform a post request on my (unchanged) server until recently. Since a couple of weeks I got a 400 bad request response. What could be the problem? A POST send with command line curl works fine.

std::ostringstream oss;
oss << "mydata";

int size = oss.tellp();
std::string test = oss.str();

boost::asio::ip::tcp::iostream stream;
stream.connect("myserver.nl", "http");
stream << "POST /dir/newdata.php  HTTP/1.1\r\n";
stream << "Host: myserver.nl\r\n";
stream << "Accept: */*\r\n";
stream << "Content-Type: application/x-www-form-urlencoded; charset=utf-8\r\n";
stream << "Content-Length: " << size << "\r\n";
stream << "Connection: close\r\n\r\n";

stream << oss.str();
stream.flush();
std::cout  << stream.rdbuf();

It now results in the following error:

HTTP/1.1 400 Bad Request
Date: Tue, 20 Feb 2018 09:22:15 GMT
Server: Apache/2.4.29 (Unix)
Content-Length: 226
Connection: close
Content-Type: text/html; charset=iso-8859-1

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>400 Bad Request</title>
</head><body>
<h1>Bad Request</h1>
<p>Your browser sent a request that this server could not understand.<br/>
</p>


Solution

  • You have an extra space between the query and the HTTP version:

    stream << "POST /dir/newdata.php HTTP/1.1\r\n";