利用 JavaSE 创建简单 HTTP Server

在工作中经常会遇到简单实用 HTTP server 的场景,可是又不需要 Spring MVC 或者 web容器那样重的东西。这种情况下 JavaSE 就可以满足我们的要求了。

上代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package web;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;

/**
* Created by zhangbo54 on 2019-01-24.
*/
@Service
public class SimpleServer {
@PostConstruct
public void initHttpServer() throws IOException {
HttpServer server = HttpServer.create(new InetSocketAddress(8418), 0);
server.createContext("/test", new MyHandler());
server.setExecutor(null); // creates a default executor
server.start();
}

static class MyHandler implements HttpHandler {
@Override
public void handle(HttpExchange httpExchange) throws IOException {
System.out.println("receive");
String requestMethod = httpExchange.getRequestMethod();
if (requestMethod.equalsIgnoreCase("GET")) {//客户端的请求是get方法
//设置服务端响应的编码格式,否则在客户端收到的可能是乱码
Headers responseHeaders = httpExchange.getResponseHeaders();
responseHeaders.set("Content-Type", "text/html;charset=utf-8");

//在这里通过httpExchange获取客户端发送过来的消息
//URI url = httpExchange.getRequestURI();
//InputStream requestBody = httpExchange.getRequestBody();

// 这里获取get请求参数
// will return string in format similar to this: "field1=value1&field2=value2&field3=value3..."
String queryParams = httpExchange.getRequestURI().getQuery();
System.out.println(queryParams);

String response = "this is server";

httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.getBytes("UTF-8").length);

try (OutputStream responseBody = httpExchange.getResponseBody();
OutputStreamWriter writer = new OutputStreamWriter(responseBody, "UTF-8")) {
writer.write(response);
}
}

}
}
}

参考

  1. CSDN
  2. stackoverflow