http协议
1. 举例
#include<netinet/in.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int sockfd;
char buffer[1024];
struct sockaddr_in server_addr;
int portnumber, nbytes;
FILE *fp;
char request[1024];
int i;
char *host = "127.0.0.1";
char *http_req = "GET /%s HTTP/1.1\r\nAccept: */*\r\n\
Accept-Language: zh-cn\r\n\
Accept-Encoding: gzip, deflate\r\n\
Host: %s:%d\r\n\
Connection: Close\r\n\r\n";
/* 客户程序开始建立 sockfd描述符 */
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) /*建立SOCKET连接*/
{
fprintf(stderr, "Socket Error:%s\a\n", strerror(errno));
exit(1);
}
/* 客户程序填充服务端的资料 */
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(80);
inet_pton(PF_INET, host, &server_addr.sin_addr);
/*连接网站*/
if(connect(sockfd, (struct sockaddr *)(&server_addr), sizeof(struct sockaddr)) == -1)
{
fprintf(stderr, "Connect Error:%s\a\n", strerror(errno));
exit(1);
}
/*准备request,将要发送给主机*/
nbytes = sprintf(request, http_req, "maintlogin.jsp", host, 80);
printf("%s", request);
/*发送http请求request*/
if(write(sockfd, request, nbytes) < 0)
{
perror("write");
}
fp = fopen("index.html", "a");
while((nbytes = read(sockfd, buffer, 1)))
{
if(i < 4)
{
if(buffer[0] == '\r' || buffer[0] == '\n')
{
i++;
}
else
{
i = 0;
}
printf("%c", buffer[0]);/*把http头信息打印在屏幕上*/
}
else
{
fwrite(buffer, 1, 1, fp);/*将http主体信息写入文件*/
i++;
if(i % 1024 == 0)
{
fflush(fp); /*每1K时存盘一次*/
}
}
}
fclose(fp);
close(sockfd);
return 0;
}
2. http_req解释
//http请求
GET /maintlogin.jsp HTTP/1.1 //文件要指定/
Accept: */* //开头不要有空格
Accept-Language: zh-cn
Host: 127.0.0.1:80
Connection: Close
//请求失败
HTTP/1.1 400 Bad Request
Server: Apache-Coyote/1.1
Date: Tue, 20 Oct 2015 05:23:24 GMT
Connection: close
//请求成功
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=UTF-8
Content-Length: 1297
Date: Tue, 20 Oct 2015 05:22:36 GMT
Connection: close
Server 响应头包含处理请求的原始服务器的软件信息
Connection:keep-alive TCP连接仍然保持打开状态
Pragma 页面缓存(1.0)
cache-control 页面缓存(1.1)
如果指定压缩,Accept-Encoding: gzip, deflate,主机头会返回压缩提示,Content-Encoding: gzip。相应的Content-Length也会减小
错误码:见百科
3. 在tcp/ip协议中的位置
http协议通常承载于tcp协议之上,有时也承载于TLS或SSL协议层之上,就成了我们常说的https。http端口是80,https端口是443
4. http消息格式