简体   繁体   中英

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. All the files are stored locally. Using Firefox to connect to server (chrome seems to block images).

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)

                {   

                    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.

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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