如何在没有 Spring、Java EE 等 Web 框架的情况下使用 Java 创建 HTTP API?
HTTP 的基础知识相当简单。打开 aServerSocket来监听传入的请求。建立连接后,启动一个新线程并发送响应。那可能看起来像,
public static void main(String[] args) {
try {
ServerSocket ss = ServerSocketFactory.getDefault().createServerSocket(8080, 10);
StringBuilder body = new StringBuilder();
body.append("<html><body><h1>Hello, World!</h1></body></html>");
while (true) {
Socket s = ss.accept();
Thread t = new Thread(new HttpReply(s, body));
t.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
然后,要实际发送响应,您可以OutputStream从 中获取Socket并写入所需的 HTTP 标头,然后是正文。喜欢,
class HttpReply implements Runnable {
private Socket s;
private StringBuilder body;
private HttpReply(Socket s, StringBuilder body) {
this.s = s;
this.body = body;
}
public void run() {
try {
PrintStream ps = new PrintStream(s.getOutputStream());
ps.println("HTTP/1.1 200 OK");
ps.println("Date: Mon, 27 Jul 2009 12:28:53 GMT");
ps.println("Server: Java");
ps.println("Last-Modified: Wed, 22 Jul 2009 19:15:56 GMT");
ps.println("Content-Length: " + body.length());
ps.println("Content-Type: text/html");
ps.println("Connection: Closed");
ps.println();
ps.println(body);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
它将在8080您的计算机端口上侦听请求并使用基本的 hello world 网页进行回复。
| 归档时间: |
|
| 查看次数: |
5593 次 |
| 最近记录: |