content-length 与 transfer-encoding=chunked

13-04-28 runc

public class HttpServerTest {

	public static void main(String[] args) throws IOException {
		HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
		server.createContext("/echo", new Handler());
		server.start();
	}
}

class Handler implements HttpHandler {
	public void handle(HttpExchange xchg) throws IOException {
		Headers headers = xchg.getRequestHeaders();
		Set<Map.Entry<String, List<String>>> entries = headers.entrySet();
		StringBuffer response = new StringBuffer();
		for (Map.Entry<String, List<String>> entry : entries)
			response.append(entry.toString() + "\n");

		xchg.sendResponseHeaders(200, response.length());
		OutputStream os = xchg.getResponseBody();
		os.write("abc".getBytes());
		// os.write(response.toString().getBytes());
		os.close();
	}

}
<p>

上面的代码,在浏览器中访问http://localhost:8000/echo出现无法显示此网页,但注释掉注释处的上面这句os.write("abc".getBytes());放开 os.write(response.toString().getBytes());则能够显示正确结果,这是上面道理呢?

还有如何从content-length转化到Transfer-Encoding:chunked呢?

猜你喜欢