content-length 與 transfer-encoding=chunked

runc發表於2013-04-28

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 class="indent">


上面的程式碼,在瀏覽器中訪問http://localhost:8000/echo出現無法顯示此網頁,但註釋掉註釋處的上面這句os.write("abc".getBytes());放開 os.write(response.toString().getBytes());則能夠顯示正確結果,這是上面道理呢?
還有如何從content-length轉化到Transfer-Encoding:chunked呢?

相關文章