Skip to content

programingjd/okserver

Repository files navigation

jcenterjcenter

okserver

A simple http server for the jvm and android, built on top of okhttp.

Download

The maven artifacts are on Bintray and jcenter.

Download the latest jar.

Maven

Include those settings to be able to resolve jcenter artifacts.

<dependency>
  <groupId>info.jdavid.ok.server</groupId>
  <artifactId>okserver</artifactId>
  <version>3.14.4.0</version>
</dependency>

Gradle

Add jcenter to the list of maven repositories.

repositories {
  jcenter()
}
dependencies {
  compile 'info.jdavid.ok.server:okserver:3.14.4.0'
}

Usage

You specify what your server does by overriding the handle method.

Here's a very simple example:

  • For a GET request to /ok, we return a 200 OK with the content "ok".
  • For any other request, we return a 404 Not Found with no content.
new HttpServer().requestHandler(
  new RequestHandler() {
    @Override
    public Response handle(final String clientIp, final boolean secure,
                           final boolean insecureOnly, final boolean http2,
                           final String method, final HttpUrl url,
                           final Headers requestHeaders,
                           final Buffer requestBody) {
      final String path = url.encodedPath();
      final Response.Builder builder = new Response.Builder();
      if ("GET".equals(method) && "/ok".equals(path)) {
        builder.statusLine(StatusLines.OK).body("ok");
      }
      else {
        builder.statusLine(StatusLines.NOT_FOUND).noBody();
      }
      return builder.build();
    }
  }
);

To start the server, you simply call start(). It defaults to port 8080, but you can change that easily with the port(int) method. It also defaults to all the ip addresses on the local machine, but you can also change that easily with the hostname(String) method.

new HttpServer().hostname("localhost").port(80).start();

If you want to use https, you can specify another port and the certificate to use for tls.

new HttpServer().
  hostname("example.com").
  ports(8080, 8181).
  https(new Https.Builder().certificate(p12, useHttp2).build()).
  start();

Requests are handled by a Dispatcher. The default implementation uses a cached thread pool. You can change the dispatcher with the dispatcher(Dispatcher) method. The Dispatcher class includes various implementations that are ready to use. You can also provide your own implementation.

Here's an example that sets a dispatcher with a single thread executor rather than a cached thread pool.

final HttpServer server = new HttpServer().dispatcher(
  new Dispatcher() {
    private ExecutorService mExecutors = null;
    @Override
    public void start() {
      mExecutors = Executors.newSingleThreadExecutor();
    }
    @Override
    public void dispatch(final HttpServer.Request request) {
      mExecutors.execute(new Runnable() {
        @Override public void run() { request.serve(); }
      });
    }
    @Override
    public void shutdown() {
      try {
        mExecutors.awaitTermination(5, TimeUnit.SECONDS);
      }
      catch (final InterruptedException ignore) {}
      mExecutors.shutdownNow();
    }
  }
);

The easiest way to implement request handlers is to use a RequestHandlerChain, and add predefined handlers to it.

final Map<String, String> credentials = new HashMap<String, String>();
credentials.put("user1", "password1");
final File webRoot = new File(new File(System.getProperty("user.home")), "www");

new HttpServer().
  requestHandler(
    new RequestHandlerChain().
      add(new BasicAuthHandler(credentials, new FileHandler(webRoot)))
  ).
  dispatcher(new Dispatcher.MultiThreadsDispatcher(4)).
  port(8080).
  start();

You can find more examples in the samples directory. These include examples for implementing Server Side Events (SSE).

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published