自建简易HTTP服务器出现ERR_EMPTY_RESPONSE错误的解决方法
解决自建HTTP服务器返回ERR_EMPTY_RESPONSE的问题
我搭建了一台自建简易HTTP服务器,在Chrome浏览器中输入地址http://localhost:8077/hello测试时,遇到如下错误:
This page isn’t working
localhost didn’t send any data.
ERR_EMPTY_RESPONSE
服务器代码如下:
package com.kpv.gateway; import com.sun.net.httpserver.HttpServer; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpExchange; import java.io.IOException; import java.io.OutputStream; public class SimpleHttpServer { public static void main(String[] args) throws IOException { // Create an HttpServer instance HttpServer server = HttpServer.create(new java.net.InetSocketAddress(8077), 0); // Create a context for a specific path and associate it with a handler server.createContext("/hello", new HelloHandler()); // Start the server server.start(); } // Define a simple handler static class HelloHandler implements HttpHandler { @Override public void handle(HttpExchange exchange) throws IOException { // Get the output stream to write the response OutputStream os = exchange.getResponseBody(); System.out.print("hello"); String htmlResponse = "<html><body><h1>Hello, World!</h1></body></html>"; os.write(htmlResponse.getBytes()); os.close(); } } }
问题原因及修复
你的代码缺失了HTTP响应的关键步骤:没有向客户端发送响应状态码和响应头,浏览器无法识别返回的内容,因此判定为"没有收到任何数据"。
修正后的代码如下:
package com.kpv.gateway; import com.sun.net.httpserver.HttpServer; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpExchange; import java.io.IOException; import java.io.OutputStream; public class SimpleHttpServer { public static void main(String[] args) throws IOException { HttpServer server = HttpServer.create(new java.net.InetSocketAddress(8077), 0); server.createContext("/hello", new HelloHandler()); server.start(); } static class HelloHandler implements HttpHandler { @Override public void handle(HttpExchange exchange) throws IOException { String htmlResponse = "<html><body><h1>Hello, World!</h1></body></html>"; byte[] responseBytes = htmlResponse.getBytes(); // 发送响应状态码和响应头 exchange.sendResponseHeaders(200, responseBytes.length); // 获取输出流并写入响应内容 OutputStream os = exchange.getResponseBody(); os.write(responseBytes); os.close(); System.out.println("hello"); } } }
关键修改点:
- 调用
exchange.sendResponseHeaders(200, responseBytes.length):第一个参数是HTTP状态码(200表示请求成功),第二个参数是响应内容的字节长度,告诉浏览器预期接收的数据大小。 - 调整代码顺序:先准备响应内容、计算字节长度,再发送响应头,最后写入内容,符合HTTP响应的规范流程。
修改后重新运行服务器,浏览器就能正常接收并解析响应内容,不会再出现ERR_EMPTY_RESPONSE错误。
内容的提问来源于stack exchange,提问作者vico
相关产品推荐
相关产品推荐

