Search code examples
javahtmlcssserver

Including CSS when writing HTML file to OutputStream in Java


I'm trying to import a pre-written index.html file and parse it to a client from a host server. I am using a StringBuilder to load up the HTML file into a string and then write it to the client. My code for the server is below:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class HTTPServer {
    public static void main(String[] args) throws IOException {
        // start server on port 8080
        ServerSocket server = new ServerSocket(8080);
        System.out.println("Listening for connection on port 8080..."); 

        while (true) {
            try {
                // accept connection from a client
                Socket socket = server.accept();
                InputStream in = socket.getInputStream();
                OutputStream out = socket.getOutputStream();

                // load HTML file from file directory
                StringBuilder contentBuilder = new StringBuilder();
                try {
                    BufferedReader webpage = new BufferedReader(new FileReader("index.html"));
                    String str;
                    while ((str = webpage.readLine()) != null) {
                        contentBuilder.append(str);
                    }
                    webpage.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                String html = contentBuilder.toString();

                // construct valid HTML response message
                final String CRLF = "\r\n"; // 13, 10
                String response = 
                    "HTTP/1.1 200 OK" + CRLF + // status line: HTTP_VERSION RESPONSE_CODE RESPONSE_MESSAGE
                    "Content-Length: " + html.getBytes().length + CRLF + // header
                    CRLF + 
                    html + 
                    CRLF + CRLF;

                // write HTML message to the client
                out.write(response.getBytes());

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

My index.html file references a style.css file that I have also written previously, but when I start this server, the HTML page on localhost is not formatted according to the aforementioned CSS file. For reference, here is what the index.html page looks like when opened normally (this is a fake church by the way!).

Does anyone know how I can get my Java server to keep intact the styling? Thanks!

I have tried looking online for a solution but have not found one. Perhaps I have to send the whole stylesheets file to the client separately?


Solution

  • Seems I just have to send the HTML and CSS separately! I just didn't know yet that HTTP would send a different request for the CSS file itself.