Java class for embedded HTTP server in Swing app
Asked Answered
N

5

31

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.

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?

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

Nitrite answered 27/7, 2009 at 3:47 Comment(0)
F
70

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

Example usage:

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();
    }
  }
}

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

Freehanded answered 27/7, 2009 at 4:3 Comment(4)
Thanks for going the extra mile and providing example code. This should be perfect for my needs, cheers!Nitrite
Sorry may I ask you one other question related to this example? Running this example, once the server is started I'm not sure how the heck to stop the thread it's running on? For example, if a client requests a special url which tells it to close, I can stop the server by calling server.stop(0) but the app itself seems to still be running?Nitrite
@Ivan - Can you tell me how can I redirect to a link with an alert message from the handle method? Thank you.Fellah
You might have an "access rules" issue if running this code under Eclipse. See this answer for how to correct this: #13156234Bouzoun
S
8

You can use jetty as embedded server, its fairly light weight. Other option is check this out for a simple java class to handle http requests http://java.sun.com/developer/technicalArticles/Networking/Webserver/.

Other way is in Java 6 you can use com.sun.net.httpserver.HttpServer

Sibeal answered 27/7, 2009 at 4:3 Comment(1)
The Java 6 web server is your best bet if your app is deployed on platoforms with Java 6.Chantalchantalle
H
3

Sun embedded web server is useful, but com.sun.net package could be dropped without notice. A better alternative are

Hobbs answered 24/6, 2011 at 14:35 Comment(0)
J
1

If you're not using Java 6, then I would certainly recommend Jetty. That works very well and has a decent programming interface.

Joannjoanna answered 27/7, 2009 at 8:56 Comment(0)
K
1

You said "very light" twice, so I think JLHTTP might be a good match for you. You can embed it as a single source file or a ~35K/50K jar file, yet it supports most functionality you'd need in an HTTP server out of the box.

Disclaimer: I'm the author. But check it out for yourself and see what you think :-)

Kiddush answered 26/2, 2016 at 14:31 Comment(2)
something like that exist for websockets?Vasques
I considered adding websocket support to JLHTTP, but it's too different and too large to be part of core JLHTTP. Maybe some day I'll get around to doing it in a separate sibling project...Kiddush

© 2022 - 2024 — McMap. All rights reserved.