什么是HTTP协议?
HTTP就是目前使用最广泛的Web应用程序使用的基础协议,例如,浏览器访问网站,手机App访问后台服务器,都是通过HTTP协议实现的。 HTTP是HyperText Transfer Protocol的缩写,翻译为超文本传输协议。 它是基于TCP协议之上的一种请求-响应协议。
(1)基于HTTP协议编写一个网站
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.UUID;
// 基于HTTP协议(应用层) + TCP协议(传输层)的服务器端
// 通过网络IP地址在浏览器中查看写入的内容
public class Main {
public static void main(String[] args) {
// 传输层使用TCP协议处理应用层请求
try (ServerSocket serverSocket = new ServerSocket(8848)) {
while(true) {
// 监听端口,等待客户端浏览器的请求
Socket clientSocket = serverSocket.accept();
// 服务器按照HTTP协议向客户端进行响应
// 响应文本
// try(OutputStream out = clientSocket.getOutputStream()){
// out.write("HTTP/1.1 200 OK\r\n".getBytes());
// out.write("Content-Type: text/html\r\n".getBytes());
// //out.write("Content-Length: 133251\r\n".getBytes());
// out.write("\r\n".getBytes());
// out.write("您本次的抽奖号码:".getBytes());
// out.write("<strong>".getBytes());
// out.write(UUID.randomUUID().toString().getBytes());
// out.write("</strong>".getBytes());
// out.flush();
// }
// 响应图片
try(OutputStream out = clientSocket.getOutputStream();
FileInputStream fis = new FileInputStream("D:\\test\\upload\\普京.jpg");){
out.write("HTTP/1.1 200 OK\r\n".getBytes());
out.write("Content-Type: image/jpeg\r\n".getBytes());
out.write(("Content-Length: "+fis.available()+"\r\n").getBytes());
out.write("\r\n".getBytes());
// 响应图片
byte[] buff = new byte[1024];
int len = -1;
while((len = fis.read(buff)) != -1) {
out.write(buff);
out.flush();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}