Swing应用程序中嵌入式HTTP服务器的Java类 [英] Java class for embedded HTTP server in Swing app

查看:257
本文介绍了Swing应用程序中嵌入式HTTP服务器的Java类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在我的Java Swing应用程序中嵌入一个非常轻便的HTTP服务器,该服务器仅接受请求,执行一些操作并返回结果.

I wish to embed a very light HTTP server in my Java Swing app which just accepts requests, performs some actions, and returns the results.

我是否可以在我的应用程序中使用一个非常轻便的Java类,该类在指定端口上侦听HTTP请求并让我处理请求?

Is there a very light Java class that I can use in my app which listens on a specified port for HTTP requests and lets me handle requests?

请注意,我并不是在寻找独立的HTTP服务器,而只是在应用程序中可以使用的小型Java类.

Note, that I am not looking for a stand-alone HTTP server, just a small Java class which I can use in my app.

推荐答案

自Java 6以来,JDK包含一个简单的

Since Java 6, the JDK contains a simple HTTP server implementation.

用法示例:

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 .它非常轻巧,非常适合此目的.

Or you can use Jetty for that purpose. It’s quite lightweight and perfectly fits this purpose.

这篇关于Swing应用程序中嵌入式HTTP服务器的Java类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆