skip to Main Content

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 = "rn"; // 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?

2

Answers


  1. Chosen as BEST ANSWER

    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.


  2. Combine every external file into one index.html

    Embedded external files (css, xxx.jpg) into one html file.

    Your original html

    ├── index.html
    ├── 001.jpg
    └── style.css
    

    index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Simple HTML Page</title>
        <!-- External CSS File -->
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <h1>Welcome to my simple web page</h1>
        <p>This is a sample web page using external CSS and images.</p>
        
        <!-- External Image File -->
        <div class="image-container">    
        <img src="001.jpg" alt="Sample pictures">
        </div>    
    </body>
    </html>
    

    style.css

    body {
        font-family: Arial, sans-serif;
        background-color: #f0f0f0;
        text-align: center;
        padding: 20px;
    }
    
    h1 {
        color: #333;
    }
    
    p {
        color: #666;
    }
    
    img {
        width: 200px;
        height: auto;
        margin-top: 20px;
    }
    

    001.jpg

    001.jpg is your image.

    New Output

    All in one – index.html

    index.html
    

    move style.css into html

        <title>Embedded Resources Example</title>
        <style>
            /* Embedded CSS */
            // COPY style.css into here
        </style>
    </head>
    

    encode image into base 64

    Run linux command:

    base64 -w 76 001.jpg > 001_base64.txt
    

    put 001_base64.txt into here

        <div class="image-container">
            <!-- Embedded Image as base64 -->
            <img src="data:image/png;base64,
             //all 001_base64.txt
             
            " alt="Sample pictures">
         </div>
    

    full index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Embedded Resources Example</title>
        <style>
            /* Embedded CSS */
            body {
                font-family: Arial, sans-serif;
                background-color: #f0f0f0;
                text-align: center;
                padding: 20px;
            }
    
            h1 {
                color: #333;
            }
    
            p {
                color: #666;
            }
    
            img {
                width: 200px;
                height: auto;
                margin-top: 20px;
            }
        </style>
    </head>
    <body>
        <h1>Welcome to Embedded Resources web page</h1>
        <p>This is a Embedded Resources web page using embedded CSS and images.</p>
        
        <div class="image-container">
            <!-- Embedded Image as base64 -->
            <img src="data:image/png;base64,
            
            /9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0a
            HBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIy
            ...
            ...
            WPDLUElPTAjZRRdzKHM6SOczBbnKY7I2WJlerTtbdjHkNFMaDwUUXBm/7v8Aj/60X/UendV4/auV
            lK9uXUxNZxUUWyhR/9k=" alt="Sample pictures">
        </div>
    
    </body>
    </html>
    

    Now you can just use this index.html to include css and image files.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search