Isabel Cariod Isabel Cariod - 2 months ago 6
C Question

GET HTTP Request in C (Message Body)

I make a GET request with C in the following code:

char buffer[1024] =
"GET / HTTP/1.1\r\n"
"Host: example.com\r\n"
"Accept-Encoding: gzip, deflate\r\n"
"Accept-Language: en-US,en;q=0.5\r\n"
"User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:47.0) Gecko/20100101 Firefox/47.0\r\n"
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n"
"Connection: keep-alive\r\n"
"Cache-Control: max-age=0\r\n\r\n";

size_t buffer_len = sizeof(buffer) - 1;

/* Send message to the server */
n = write(sockfd, buffer, buffer_len);

/* Now read server response */
bzero(buffer, strlen(buffer));
n = read(sockfd, buffer, buffer_len);

/* Display result */
printf("%s\n",buffer);
return 0;


Properly respond:

HTTP/1.1 200 OK
Date: Mon, 19 Sep 2016 17:20:48 GMT
Server: Apache
Content-Encoding: gzip
Vary: Accept-Encoding
Content-Length: 6695
Keep-Alive: timeout=2, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=UTF-8




Except for the last line which should be Message Body,
instead of html content It appears only a symbol �, Does anyone know where can be the problem?

Answer

You told the server that you are willing to accept a compressed response (see Accept-Encoding: gzip, deflate), so the server actually sent you a gzip-compressed response (see Content-Encoding: gzip). Your code does not actually support decompression (you can use the zlib library for that), so you need to remove Accept-Encoding from your request header. Then you will get a response with a message body that is not compressed.

Comments