简体   繁体   English

如何使用Java将HTTP响应正确发送到客户端

[英]How to properly send HTTP response to Client in Java

I'm in process of making a Server to display a HTML page as a college assessment. 我正在制作服务器以显示HTML页面作为大学评估。 All the files are stored locally. 所有文件都存储在本地。 Using Firefox to connect to server (chrome seems to block images). 使用Firefox连接到服务器(Chrome似乎阻止了图像)。

The code below works fine if i type a HTTP Response in the HTML file itself that's being transferred (I'm typing 'HTTP/1.1 200 OK' at start of HTML file) 如果我在要传输的HTML文件本身中键入HTTP响应,则下面的代码可以正常工作(我在HTML文件开头输入“ HTTP / 1.1 200 OK”)

                {   

                    byte[] pageToBytes = Files.readAllBytes(webContent.toPath());

                    os.write(pageToBytes); 
                    os.flush();
                    os.close();                  

                }

But if i try and send HTTP response first ,then HTML after, it refuses to load the images in my specified in my HTML code. 但是,如果我尝试先发送HTTP响应,然后再发送HTML,则它拒绝将图像加载到HTML代码中指定的图像中。

Here is Code i'm trying to figure out problem with: 这是我试图找出问题的代码:

                 {  

                    byte[] pageToBytes = Files.readAllBytes(webContent.toPath());


                    String HttpOK = "HTTP/1.1 200 OK\n\r";

                    os.write(HttpOK.getBytes());                        
                    os.write(pageToBytes); 
                    os.flush();
                    os.close();                  

                }

Any insights would be much appreciated :) 任何见解将不胜感激:)

You should read about HTTP requests, when the browser makes a request open a channel of communication between the server and the client, which is the stream you are writing to, this channel closes once the client has received a response. 您应该阅读有关HTTP请求的信息,当浏览器发出请求打开服务器和客户端之间的通信通道(即您正在写入的流)时,一旦客户端收到响应,该通道就会关闭。

In your code you are responding once, but the second time the stream is already closed that's why the response body is never reaching the client. 在您的代码中,您只响应一次,但是第二次关闭流时,这就是响应主体永远不会到达客户端的原因。 Also the server automatically sends a 200 code when there is no error or the code says otherwise. 此外,如果没有错误或代码另有说明,则服务器会自动发送200代码。

由于您正在尝试制作http服务器,因此在此处进行介绍很不错,它说明了如何处理http请求和响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM