前言
有时候,我们需要用Java开发一个小的程序,或者只需要实现简单的http监听的server,此时并不想引入太多依赖(比如Spring或者要使用Tomcat等),此时可以使用Java自带的HttpServer来实现简单的web服务器,实现一些基本功能还是没有问题的。
实现
下面分享下代码片段实现HttpServer,代码实现了以下几个功能和要点(详见代码注释):
- 实现web server(GET方法): http://127.0.0.1:8182/hello
- 如果GET携带参数 http://127.0.0.1:8182/hello?msg=hello&type=1 可以解析参数(queryToMap)
- 返回中带中文问题
- 实现简单的Basic Auth认证
- 实现web server(POST方法): http://127.0.0.1:8182/post,并解析出参数
- 返回简单的HTML代码
import com.sun.net.httpserver.BasicAuthenticator;
import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
public class SimpleHttpServer {
public static void main(String[] args) throws Exception {
// 监听8182端口
HttpServer httpServer = HttpServer.create(new InetSocketAddress(8182), 0);
// http://127.0.0.1:8182/hello
HttpContext cc = httpServer.createContext("/hello", new HelloHandler());
// basic auth 简单验证
cc.setAuthenticator(new AuthVerify("Restricted Area"));
//用lambda方式演示,post方法,并返回简单的HTML(处理中文问题)
httpServer.createContext("/post", httpExchange -> {
InputStream input = httpExchange.getRequestBody();
StringBuilder stringBuilder = new StringBuilder();
new BufferedReader(new InputStreamReader(input))
.lines()
.forEach((String s) -> stringBuilder.append(s).append("\n"));
String response = "<html>\n"
+ "<body>\n"
+ "\n"
+ "<h4>"
+ "收到的参数是:"+stringBuilder
+ "</h4>"
+ "</body>\n"
+ "</html> ";
// 如果有中文,response.getBytes 需要加上UTF-8
httpExchange.sendResponseHeaders(200, response.getBytes(StandardCharsets.UTF_8).length);
OutputStream output = httpExchange.getResponseBody();
output.write(response.getBytes(StandardCharsets.UTF_8));
output.flush();
output.close();
httpExchange.close();
});
httpServer.setExecutor(Executors.newCachedThreadPool());
httpServer.start();
}
static class HelloHandler implements HttpHandler {
@Override
public void handle(HttpExchange httpExchange) throws IOException {
String query = httpExchange.getRequestURI().getQuery();
String response = "HelloWorld, 收到的参数是: " + query;
// 可以使用queryToMap(query) 工具方法,把query转成map
httpExchange.sendResponseHeaders(200, response.getBytes(StandardCharsets.UTF_8).length);
OutputStream os = httpExchange.getResponseBody();
// 如果有中文,response.getBytes 需要加上UTF-8
os.write(response.getBytes(StandardCharsets.UTF_8));
os.flush();
os.close();
}
}
static class AuthVerify extends BasicAuthenticator {
public AuthVerify(String s) {
super(s);
}
@Override
public boolean checkCredentials(String username, String password) {
return "admin".equals(username) && "password".equals(password);
}
}
public static Map<String, String> queryToMap(String query) {
Map<String, String> result = new HashMap<>();
for (String param : query.split("&")) {
String[] entry = param.split("=");
if (entry.length > 1) {
result.put(entry[0], entry[1]);
} else {
result.put(entry[0], "");
}
}
return result;
}
}
import com.sun.net.httpserver.BasicAuthenticator;
import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
public class SimpleHttpServer {
public static void main(String[] args) throws Exception {
// 监听8182端口
HttpServer httpServer = HttpServer.create(new InetSocketAddress(8182), 0);
// http://127.0.0.1:8182/hello
HttpContext cc = httpServer.createContext("/hello", new HelloHandler());
// basic auth 简单验证
cc.setAuthenticator(new AuthVerify("Restricted Area"));
//用lambda方式演示,post方法,并返回简单的HTML(处理中文问题)
httpServer.createContext("/post", httpExchange -> {
InputStream input = httpExchange.getRequestBody();
StringBuilder stringBuilder = new StringBuilder();
new BufferedReader(new InputStreamReader(input))
.lines()
.forEach((String s) -> stringBuilder.append(s).append("\n"));
String response = "<html>\n"
+ "<body>\n"
+ "\n"
+ "<h4>"
+ "收到的参数是:"+stringBuilder
+ "</h4>"
+ "</body>\n"
+ "</html> ";
// 如果有中文,response.getBytes 需要加上UTF-8
httpExchange.sendResponseHeaders(200, response.getBytes(StandardCharsets.UTF_8).length);
OutputStream output = httpExchange.getResponseBody();
output.write(response.getBytes(StandardCharsets.UTF_8));
output.flush();
output.close();
httpExchange.close();
});
httpServer.setExecutor(Executors.newCachedThreadPool());
httpServer.start();
}
static class HelloHandler implements HttpHandler {
@Override
public void handle(HttpExchange httpExchange) throws IOException {
String query = httpExchange.getRequestURI().getQuery();
String response = "HelloWorld, 收到的参数是: " + query;
// 可以使用queryToMap(query) 工具方法,把query转成map
httpExchange.sendResponseHeaders(200, response.getBytes(StandardCharsets.UTF_8).length);
OutputStream os = httpExchange.getResponseBody();
// 如果有中文,response.getBytes 需要加上UTF-8
os.write(response.getBytes(StandardCharsets.UTF_8));
os.flush();
os.close();
}
}
static class AuthVerify extends BasicAuthenticator {
public AuthVerify(String s) {
super(s);
}
@Override
public boolean checkCredentials(String username, String password) {
return "admin".equals(username) && "password".equals(password);
}
}
public static Map<String, String> queryToMap(String query) {
Map<String, String> result = new HashMap<>();
for (String param : query.split("&")) {
String[] entry = param.split("=");
if (entry.length > 1) {
result.put(entry[0], entry[1]);
} else {
result.put(entry[0], "");
}
}
return result;
}
}
import com.sun.net.httpserver.BasicAuthenticator; import com.sun.net.httpserver.HttpContext; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Executors; public class SimpleHttpServer { public static void main(String[] args) throws Exception { // 监听8182端口 HttpServer httpServer = HttpServer.create(new InetSocketAddress(8182), 0); // http://127.0.0.1:8182/hello HttpContext cc = httpServer.createContext("/hello", new HelloHandler()); // basic auth 简单验证 cc.setAuthenticator(new AuthVerify("Restricted Area")); //用lambda方式演示,post方法,并返回简单的HTML(处理中文问题) httpServer.createContext("/post", httpExchange -> { InputStream input = httpExchange.getRequestBody(); StringBuilder stringBuilder = new StringBuilder(); new BufferedReader(new InputStreamReader(input)) .lines() .forEach((String s) -> stringBuilder.append(s).append("\n")); String response = "<html>\n" + "<body>\n" + "\n" + "<h4>" + "收到的参数是:"+stringBuilder + "</h4>" + "</body>\n" + "</html> "; // 如果有中文,response.getBytes 需要加上UTF-8 httpExchange.sendResponseHeaders(200, response.getBytes(StandardCharsets.UTF_8).length); OutputStream output = httpExchange.getResponseBody(); output.write(response.getBytes(StandardCharsets.UTF_8)); output.flush(); output.close(); httpExchange.close(); }); httpServer.setExecutor(Executors.newCachedThreadPool()); httpServer.start(); } static class HelloHandler implements HttpHandler { @Override public void handle(HttpExchange httpExchange) throws IOException { String query = httpExchange.getRequestURI().getQuery(); String response = "HelloWorld, 收到的参数是: " + query; // 可以使用queryToMap(query) 工具方法,把query转成map httpExchange.sendResponseHeaders(200, response.getBytes(StandardCharsets.UTF_8).length); OutputStream os = httpExchange.getResponseBody(); // 如果有中文,response.getBytes 需要加上UTF-8 os.write(response.getBytes(StandardCharsets.UTF_8)); os.flush(); os.close(); } } static class AuthVerify extends BasicAuthenticator { public AuthVerify(String s) { super(s); } @Override public boolean checkCredentials(String username, String password) { return "admin".equals(username) && "password".equals(password); } } public static Map<String, String> queryToMap(String query) { Map<String, String> result = new HashMap<>(); for (String param : query.split("&")) { String[] entry = param.split("="); if (entry.length > 1) { result.put(entry[0], entry[1]); } else { result.put(entry[0], ""); } } return result; } }
文章评论