1、HTTP协议详解
参考文档:HTTP协议详解及使用
2、Java实现HTTP协议客户端
客户端(例如Web浏览器)向服务器发送HTTP请求。请求由请求行、请求头部和请求体组成。请求行包含请求方法(GET、POST等)、请求的URL和HTTP协议版本。
import java.io.*; import java.net.Socket; // HTTP 客户端 public class HTTPClient { public static void main(String[] args) throws IOException { // 1. HTTP 客户端,要发送 HTTP 请求,先建立 TCP 连接 // 我们当前进程和www.baidu.com主机上绑定 8080 端口的进程使用 TCP 通信(要求 建立 TCP 连接) Socket socket = new Socket("localhost", 80); OutputStream os = socket.getOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(os, "UTF-8")); // 只有请求行,请求头为空,没有请求体 String request = "GET / HTTP/1.0\r\n\r\n"; writer.print(request); // 冲刷缓冲区 writer.flush(); // 读取百度返回的 HTTP 响应 InputStream is = socket.getInputStream(); byte[] buf = new byte[10240]; // 不超过 1024 字节的数据 int n = is.read(buf); String response = new String(buf, 0, n, "UTF-8"); System.out.println(response); } }
3、Java实现HTTP协议服务端
服务器接收处理请求,并将请求处理结果返回客户端。
import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; // HTTP 服务端 public class HTTPServer { public static void main(String[] args) throws IOException { // 我们使用短连接 ServerSocket serverSocket = new ServerSocket(80); while (true) { try { Socket socket = serverSocket.accept(); // 统一的响应回复对方 OutputStream os = socket.getOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(os, "UTF-8")); String html = "百度一">https://www.baidu.com/'>百度一下"; // 响应体的内容 byte[] bytes = html.getBytes("UTF-8"); int contentLength = bytes.length; String response = "HTTP/1.0 200 OK\r\n" + "Content-Type: application/octet-stream; charset=utf-8\r\n" + "Content-Length: 49\r\n" + "\r\n" + html; writer.print(response); writer.flush(); socket.close(); } catch (IOException exc) { exc.printStackTrace(); } } } }