Max Frai
Max Frai

Reputation: 64266

Binary data in post request

I have read the docs about http requests and wrote final this headers:

int *binary = new int[bufferLength]; // And fill it

std::stringstream out;
out << "POST /push1_pub?id=game HTTP/1.1\r\n";
out << "User-Agent: Lotosoft soccer client\r\n";
out << "Host: localhost\r\n";
out << "Accept: */*\r\n";
out << "Content-Type: application/octet-stream\r\n";
out << "Content-Length: " << bufferLength << "\r\n\r\n";

// Take out string from stream
std::string headers = out.str();
// Length of new array of bytes (headers + binary data + \0)
const int rawLen = headers.size() + bufferLength*sizeof(int) + 1;

char *raw = new char[rawLen];
// Copy headers data into bytes array
strcpy(raw, headers.c_str());
// Apply offset to bytes array and fill another part with binary array of ints
memcpy(raw+headers.size(), binary, bufferLength*sizeof(int));

std::cout << raw << std::endl;

// Send it to socket
if (socket.send(raw, rawLen) == -1)
{
    std::cout << "Failed to send headers\n";
}

Post request sends successfull, but I'm not sure everything is fine with my idea to fill everything into byte array. Is that the right way to pass binary data as post-request body?

Upvotes: 0

Views: 1563

Answers (1)

David Schwartz
David Schwartz

Reputation: 182743

Ask yourself this question: "What is the first byte of post data that I send to the server?". Do you see that you don't know -- it's whatever your platform happens to store as the first byte of the array, which will depend on how your particular CPU stores integers.

The server has no idea how your CPU stores integers, so you are sending it information there is no possible way it could make sense out of. You have to send the server a query that consists of bytes in whatever format the server expects, not whatever server your platform likes.

Also, you tell the server that you are going to send it bufferLength bytes, but then you send it bufferLength*sizeof(int) bytes. You must be consistent. (Presumably, you aren't on a platform that uses one-byte integers.)

Upvotes: 1

Related Questions