最代码广告位
最代码官方的gravatar头像
最代码官方2014-11-28 11:43:05

分享java最简单web server代码,只支持一个http get请求

package com.zuidaima.simpleserver;

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

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

/*
 * a simple static http server
 * @author www.zuidaima.com
 */
public class SimpleHttpServer {

	public static void main(String[] args) throws Exception {
		HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
		server.createContext("/zuidaima", new MyHandler());
		server.setExecutor(null); // creates a default executor
		server.start();
	}

	static class MyHandler implements HttpHandler {
		public void handle(HttpExchange t) throws IOException {
			String response = "www.zuidaima.com";
			t.sendResponseHeaders(200, response.length());
			OutputStream os = t.getResponseBody();
			os.write(response.getBytes());
			os.close();
		}
	}

}

访问:http://localhost:8000/zuidaima

分享java最简单web server代码,只支持一个http get请求

顶部客服微信二维码底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友