読者です 読者をやめる 読者になる 読者になる

or1ko's diary

日々を書きます

HTTP サーバの例(POST)

HTTP サーバ。POSTの例。

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

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

public class PostHttpServer {
	public static void main(String[] args) throws IOException {
		int port = 8080;

		HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
		server.createContext("/", new HttpHandler() {
			@Override
			public void handle(HttpExchange arg0) throws IOException {
				BufferedReader reader = new BufferedReader(new InputStreamReader(arg0.getRequestBody(), StandardCharsets.UTF_8));


				StringBuilder builder = new StringBuilder();
				String line;
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}

				String s = builder.toString();
				arg0.sendResponseHeaders(200, s.length());
				BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(arg0.getResponseBody(), StandardCharsets.UTF_8));
				writer.write(s);
				writer.flush();
			}
		});
		server.start();

		System.out.println("hit any key");
		System.in.read();
		server.stop(0);
	}
}