Swing应用程序中嵌入式HTTP服务器的Java类

Swing应用程序中嵌入式HTTP服务器的Java类,第1张

Swing应用程序中嵌入式HTTP服务器的Java类

从Java
6开始,JDK包含一个简单的HTTP服务器实现。

用法示例

import java.io.IOException;import java.io.OutputStream;import java.net.InetSocketAddress;import java.util.Iterator;import java.util.List;import java.util.Set;import java.util.concurrent.Executors;import com.sun.net.httpserver.Headers;import com.sun.net.httpserver.HttpExchange;import com.sun.net.httpserver.HttpHandler;import com.sun.net.httpserver.HttpServer;public class HttpServerDemo {  public static void main(String[] args) throws IOException {    InetSocketAddress addr = new InetSocketAddress(8080);    HttpServer server = HttpServer.create(addr, 0);    server.createContext("/", new MyHandler());    server.setExecutor(Executors.newCachedThreadPool());    server.start();    System.out.println("Server is listening on port 8080" );  }}class MyHandler implements HttpHandler {  public void handle(HttpExchange exchange) throws IOException {    String requestMethod = exchange.getRequestMethod();    if (requestMethod.equalsIgnoreCase("GET")) {      Headers responseHeaders = exchange.getResponseHeaders();      responseHeaders.set("Content-Type", "text/plain");      exchange.sendResponseHeaders(200, 0);      OutputStream responseBody = exchange.getResponseBody();      Headers requestHeaders = exchange.getRequestHeaders();      Set<String> keySet = requestHeaders.keySet();      Iterator<String> iter = keySet.iterator();      while (iter.hasNext()) {        String key = iter.next();        List values = requestHeaders.get(key);        String s = key + " = " + values.toString() + "n";        responseBody.write(s.getBytes());      }      responseBody.close();    }  }}

或者,您可以将Jetty用于此目的。它非常轻巧,非常适合此目的。



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5565050.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-14
下一篇 2022-12-14

发表评论

登录后才能评论

评论列表(0条)

保存