我在下面的代码中用C发出GET请求:
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;
正确回应:
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
�
除了最后一行应该是Message Body, 而不是html内容它只显示符号 ,有谁知道问题出在哪里?
答案 0 :(得分:4)
您告诉服务器您愿意接受压缩响应(请参阅Accept-Encoding: gzip, deflate
),因此服务器实际上向您发送了gzip压缩响应(请参阅Content-Encoding: gzip
)。您的代码实际上不支持解压缩(您可以使用zlib library),因此您需要从请求标头中删除Accept-Encoding
。然后,您将获得一个未压缩的消息体的响应。