基于java的一个简单http服务
程序员文章站
2022-04-23 11:58:21
...
基于java的一个简单http服务
代码来自网上,具体出处忘记了,copy过来后做了简单适配,时间已经挺久的了,现在发现可能要用到,就做个记录:
MyHttpHandler.java
package com.HttpProxy;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Map;
import java.util.List;
import java.util.stream.Collectors;
public class MyHttpHandler implements HttpHandler {
public void handle (HttpExchange httpExchange) {
try {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("method: ").append(httpExchange.getRequestMethod()).append("<br/>");
stringBuilder.append("request: ").append(getRequestParam(httpExchange)).append("<br/>");
stringBuilder.append("request header: ").append(getRequestHeader(httpExchange));
handleResponse(httpExchange, stringBuilder.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
private String getRequestHeader (HttpExchange httpExchange) {
Headers headers = httpExchange.getRequestHeaders();
return headers.entrySet().stream().
map((Map.Entry<String, List<String>> entry) -> ((Map.Entry) entry).getKey() + ":" + ((Map.Entry) entry).getValue().toString())
.collect(Collectors.joining("<br/>"));
}
private String getRequestParam (HttpExchange httpExchange) throws Exception{
String paramStr = "";
if (httpExchange.getRequestMethod().equals("GET")) {
paramStr = httpExchange.getRequestURI().getQuery();
} else {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpExchange.getRequestBody(), "utf-8"));
StringBuilder stringBuilder = new StringBuilder();
String line = "";
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
paramStr = stringBuilder.toString();
}
return paramStr;
}
private void handleResponse (HttpExchange httpExchange, String response) throws Exception {
StringBuilder responseContent = new StringBuilder();
responseContent.append("<html>").append("<body>").append(response)
.append("</body>").append("</html>");
String responseContentStr = responseContent.toString();
byte[] responseByte = responseContentStr.getBytes("utf-8");
// 设置响应头,必须在 sendResponseHeaders 方法之前设置
httpExchange.getResponseHeaders().add("Content-Type:", "text/html;chatset=utf-8");
// 设置响应码和响应体长度,必须在 getResponseBody 方法之前调用
httpExchange.sendResponseHeaders(200, responseByte.length);
OutputStream out = httpExchange.getResponseBody();
out.write(responseByte);
out.flush();
out.close();
}
}
HttpServerStarter.java
package com.HttpProxy;
import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
public class HttpServerStarter {
public static void main(String[] args) throws Exception {
// 创建HttpServer实例并绑定到指定的地址和端口号
HttpServer httpServer = HttpServer.create(new InetSocketAddress(8080), 0);
// 创建HttpContext,将路径为 /myserver 请求映射到MyHttpHandler处理器上
httpServer.createContext("/myserver", new MyHttpHandler());
// 设置服务器的线程池对象
httpServer.setExecutor(Executors.newFixedThreadPool(10));
// 启动服务器
httpServer.start();
}
}
上一篇: java开发一个native方法
下一篇: Java多线程-模拟一个缓存代理