HTTP/1.1 header parser received no bytes错误排查求助
HTTP/1.1 header parser received no bytes错误排查求助
我一直碰到这个错误,试了各种办法——换JVM、调整代码逻辑,就连ChatGPT都没能给出有效的解决方向。实在找不到头绪了,有没有大佬能帮忙分析下问题出在哪?我真的想搞明白这段代码到底哪里有问题。
以下是我的代码:
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.nio.file.Files; import java.nio.file.Path; public class HttpServer { private final int port; public HttpServer(final int port) { this.port = port; } public void run() { try(var serverSocket = new ServerSocket(port)) { var socket = serverSocket.accept(); System.out.println("Socket accepted"); processSocket(socket); } catch (IOException e) { throw new RuntimeException(e); } } private void processSocket(Socket socket) throws IOException { try(socket; var inputStream = new DataInputStream(socket.getInputStream()); var outputStream = new DataOutputStream(socket.getOutputStream())) { System.out.println(new String(inputStream.readNBytes(100))); byte[] body = Files.readAllBytes(Path.of("src/main/resources/example.html")); outputStream.write(""" HTTP/1.1 200 OK content-type: text/html content-length: %s """.formatted(body.length).getBytes()); outputStream.write(System.lineSeparator().getBytes()); outputStream.write(body); } catch (IOException e) { throw new RuntimeException(e); } } }
import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.file.Path; import java.util.concurrent.ExecutionException; import static java.net.http.HttpRequest.BodyPublishers.ofFile; public class HttpClientRunner { public static void main(final String[] args) throws IOException, InterruptedException, ExecutionException { var httpClient = HttpClient.newBuilder() .version(HttpClient.Version.HTTP_1_1) .build(); var request = HttpRequest.newBuilder() .uri(URI.create("http://localhost:8082")) .header("content-type", "application/json") .POST(ofFile(Path.of("src/main/resources/example.json"))) .build(); var response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.headers()); System.out.println(response.body()); } }
我已经搜遍了各种资料,完全找不到能解决这个问题的相关内容,实在是没办法了。
备注:内容来源于stack exchange,提问作者Lem
相关产品推荐
相关产品推荐

