0、先将以下代码运行起来:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
public class HttpServer {
public static void main(String[] args) throws Exception{
//开启一个服务端Socket,监听12345端口
ServerSocket server = new ServerSocket(12345);
//有客户端连进来
Socket client = server.accept();
//获取到客户端输入流
InputStream in = client.getInputStream();
//准备一个缓冲数组
byte data[]=new byte[4096];
//这里有一个read(byte[] b)方法,将数据读取到字节数组中,同返回读取长度
int len=in.read(data);
//打印浏览器发来的请求头
System.out.println(new String(data));
//制作响应报文
StringBuffer response = new StringBuffer();
//响应状态
response.append("HTTP/1.1 200 OK\r\n");
//响应头
response.append("Content-type:text/html\r\n\r\n");
//要返回的内容(当前时间)
response.append("CurrentTime: ").append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
//获取客户端的输出流
OutputStream out=client.getOutputStream();
//将以上内容写入
out.write(response.toString().getBytes());
//关闭客户端和服务端的流和Socket
out.close();
in.close();
client.close();
server.close();
}
}
1、运行起来之后,你就可以在服务器输入以下地址访问了:
http://localhost:12345/hello?param=world
2、控制台将打印如下的HTTP请求报文信息(代码第26行执行打印):
GET /hello?param=world HTTP/1.1
Host: localhost:12345
Connection: keep-alive
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
3、由于我们在代码中返回了当前时间作为响应体(在第39行加入的返回数据),而且是text/html,程序会解析为text/html,所以在浏览器就会显示:
CurrentTime: 2019-02-15 11:15:30
4、至此,一个Java实现的HTTP服务器就完成了,只要请求localhost:12345,无论什么URL,都可以返回当前时间。