Http协议基于Tcp协议。

相对于TCP协议:

  • 规定客户端需要发过来什么格式的信息,服务器需要返回什么格式的信息,通过格式服务器或者客户端就能根据规定解析得到对方传递过来的内容。

  • 短连接,客户端连接服务器,服务器返回信息后主动断开连接。

最简单的Http服务器

​ 1.首先,通过浏览器访问我们的服务器。

public class HttpServerDemo01 {
	public static void main(String[] args) throws IOException {
		ServerSocket serverSocket = new ServerSocket(8111);
		Socket accept = serverSocket.accept();
        OutputStream outputStream = accept.getOutputStream();
        //真实内容
        String content = "<html><body><h1>Hello World!</h1></body></html>";
        //按照协议,拼接返回内容
        String response = "HTTP/1.1 200 OK\r\n" + 
            			"Content-Type: text/html; charset=utf-8\r\n"  +
            			"Content-Length: "+content.getBytes().length + "\r\n"  +
            			"\r\n"+
            			content
		outputStream.write(buildHttpResponse().getBytes());
	}
}

返回内容解析

HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 47

<html><body><h1>Hello World!</h1></body></html>
  • 协议版本:HTTP1.1。
  • 响应码:200。200为成功,我们常见的404响应码,可以通过改动这个地方。
  • 返回的数据类型:Content-Type: text/html; 这个数据类型表示html,浏览器会解析为html并且渲染在界面上。
  • 字符集:charset=utf-8。
  • 空行: 这个空行将上面协议内容和真正的数据隔离开。不可删除
  • 返回的数据:这个就是服务器真正返回给浏览器的数据。
  • 要注意的点:上面的返回内容,一行都是使用回车换行(\r\n)。