利用JDK自帶的com.sun.net.httpserver.HttpServer庫侯繁,不需要依賴任何其他第三方庫,可輕松編寫部署一個web服務(wù)
代碼
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
public class MyHttpServer {
public static void main(String[] args) {
try {
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/", httpExchange -> {
String response = "{\"code\":\"200\"}";
httpExchange.sendResponseHeaders(200, response.getBytes().length);
try (OutputStream os = httpExchange.getResponseBody()) {
os.write(response.getBytes());
}
});
server.setExecutor(Executors.newCachedThreadPool());
server.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}