com.sun.net.httpserver create web Service

Keywords: Programming Java JSON curl

I started to learn Java web programming by writing a servlet, rewriting the service method, configuring the web.xml file, and finally deploying it to tomcat or jetty container and starting it. Later, I used some frameworks, struts 2 spring MVC. Today, I rummaged through the source code of JDK and found that the web service can be created very quickly by using the API provided under the package com.sun.net.httpserver. Its creation method is very similar to that of golang.

HttpHandler

First, implement HttpHandler and override the handle method.

public class MyHandler implements HttpHandler {
    @Override
    public void handle(HttpExchange httpExchange) throws IOException {
    
    }
}

Create a web service

Create a web service and register the handler created previously, and use the handler to process the request.

public class Main {

    public static void main(String[] args) {
        try {
            HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
            server.createContext("/web", new MyHandler());
            // Use the default extractor
            server.setExecutor(null);
            server.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

As long as you run this main method, a web service will start. The listening port is 8000. Here are two complete examples I wrote.

GetHandler

package me.deweixu.handler;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import netscape.javascript.JSObject;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

/**
 * Created by simeone
 *
 * @author: simeone
 * @Date: 2018/5/19
 */
public class GetHandler implements HttpHandler {
    @Override
    public void handle(HttpExchange httpExchange) throws IOException {
        System.out.println("Method: " + httpExchange.getRequestMethod());
        String param = httpExchange.getRequestURI().getQuery();
        System.out.println("Param:" + param);
        httpExchange.sendResponseHeaders(200, 0);

        OutputStream os = httpExchange.getResponseBody();
        os.write(param.getBytes());
        os.close();
    }

}

PostHandler

package me.deweixu.handler;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.UnsupportedEncodingException;

/**
 * Created by simeone
 *
 * @author: simeone
 * @Date: 2018/5/19
 */
public class PostHandler implements HttpHandler {
    @Override
    public void handle(HttpExchange httpExchange) throws IOException {
        System.out.println("Method: " + httpExchange.getRequestMethod());

        InputStream is = httpExchange.getRequestBody();
        String response = is2string(is);
        System.out.println("response: " + response);
        is.close();
        httpExchange.sendResponseHeaders(200, response.length());

        Headers headers = httpExchange.getResponseHeaders();
        headers.set("Content-Type", "application/json; charset=utf8");

        OutputStream os = httpExchange.getResponseBody();
        os.write(response.getBytes());
        os.close();
    }

    private String is2string(InputStream is) throws IOException {
        final int bufferSize = 1024;
        final char[] buffer = new char[bufferSize];
        final StringBuilder out = new StringBuilder();
        Reader in = new InputStreamReader(is, "UTF-8");
        for (; ; ) {
            int rsz = in.read(buffer, 0, buffer.length);
            if (rsz < 0)
                break;
            out.append(buffer, 0, rsz);
        }
        return out.toString();
    }
}

Main

package me.deweixu;

import com.sun.net.httpserver.HttpServer;
import me.deweixu.handler.GetHandler;
import me.deweixu.handler.PostHandler;

import java.io.IOException;
import java.net.InetSocketAddress;

public class Main {

    public static void main(String[] args) {
        try {
            HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
            server.createContext("/post", new PostHandler());
            server.createContext("/get", new GetHandler());
            server.setExecutor(null);
            server.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

test

# get
$ curl http://127.0.0.1:8000/get\?name\=simeone\&address\=beijing
name=simeone&address=beijing

# post
$ curl -H "Content-Type: application/json" -d '{"username":"simeone", "address":"beijing"}' http://127.0.0.1:8000/post
{"username":"simeone", "address":"beijing"}

Posted by rgermain on Tue, 10 Dec 2019 11:22:09 -0800