import cn.hutool.core.date.DateUtil;
import com.sun.net.httpserver.HttpServer;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.net.InetSocketAddress;
@Slf4j
public class SimpleHttpServer {
public static void main(String[] args) throws IOException {
HttpServer httpServer = HttpServer.create(new InetSocketAddress(11000), 100);
httpServer.createContext("/", new MyHandler());
httpServer.setExecutor(null);
log.info("服务启动:{}", DateUtil.now());
httpServer.start();
}
}
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Singleton;
import com.panku.service.GatewayService;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
@Slf4j
class MyHandler implements HttpHandler {
@Override
public void handle(HttpExchange httpExchange) throws IOException {
InputStream is = httpExchange.getRequestBody();
String param = IoUtil.read(is, Charset.forName("utf-8"));
is.close();
log.info("获取到信息:{}", param);
GatewayService gatewayService = Singleton.get(GatewayService.class);
String enter = gatewayService.enter(param);
log.info("响应内容:{}", enter);
Headers headers = httpExchange.getResponseHeaders();
headers.set("Content-Type", "application/json; charset=utf-8");
headers.set("Access-Control-Allow-Origin", "*");
headers.set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
headers.set("Access-Control-Max-Age", "3600");
httpExchange.sendResponseHeaders(200, enter.getBytes().length);
OutputStream os = httpExchange.getResponseBody();
OutputStreamWriter writer = new OutputStreamWriter(os, StandardCharsets.UTF_8);
writer.write(enter);
writer.close();
os.close();
httpExchange.close();
}
}