MockServer.java 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. package com.wj.other;
  2. import com.sun.net.httpserver.HttpServer;
  3. import java.io.IOException;
  4. import java.io.OutputStream;
  5. import java.net.InetSocketAddress;
  6. public class MockServer {
  7. public static void startServer() throws IOException {
  8. // 创建一个HTTP服务器,监听本地的9999端口
  9. HttpServer server = HttpServer.create(new InetSocketAddress(9990), 0);
  10. // 设置根路径的处理器
  11. server.createContext("/", httpExchange -> {
  12. // 假设所有POST请求都成功
  13. if ("POST".equals(httpExchange.getRequestMethod())) {
  14. // 发送HTTP状态码200
  15. httpExchange.sendResponseHeaders(200, 0);
  16. OutputStream os = httpExchange.getResponseBody();
  17. os.write("Success".getBytes());
  18. os.close();
  19. } else {
  20. // 其他请求方法返回错误
  21. httpExchange.sendResponseHeaders(405, 0); // 405 Method Not Allowed
  22. OutputStream os = httpExchange.getResponseBody();
  23. os.write("Method Not Allowed".getBytes());
  24. os.close();
  25. }
  26. });
  27. // 启动服务器
  28. server.start();
  29. System.out.println("Mock server started on port 9990");
  30. }
  31. public static void main(String[] args) throws IOException {
  32. startServer();
  33. }
  34. }