Wie kann ich eine HTTP-Antwort nur mit Standard-Netzwerkbibliotheken senden?

Ich arbeite an meinem ersten Hausaufgabenprojekt in einem Webprogrammierkurs, bei dem ein einfacher Webserver in Java geschrieben werden soll. Ich bin an dem Punkt angelangt, an dem Daten hin und her übertragen werden, und für das ungeübte Auge scheint mein Babyserver einwandfrei zu funktionieren. Ich kann jedoch keine Möglichkeit finden, entsprechende Antworten zu senden. (Mit anderen Worten, eine ungültige Seitenanforderung würde eine HTML-Seite mit 404-Format anzeigen, aber dennoch den Status 200 OK zurückgeben, wenn ich Antwortheader anzeige.)

Ich kann nur Standard-Netzwerkbibliotheken für die Socket-Verwaltung und Standard-E / A-Bibliotheken zum Lesen und Schreiben von Bytes und Zeichenfolgen aus einem Eingabestream verwenden. Hier ist ein passender Code:

Von meinem ...

            ServerSocket servSocket = new ServerSocket(port, 10);           // Bind the socket to the port
        System.out.println("Opened port " + port + " successfully!");

                while(true) {
            //Accept the incoming socket, which means that the server process will
            //wait until the client connects, then prepare to handle client commands
            Socket newDataSocket = servSocket.accept();
            System.out.println("Client socket created and connected to server socket...");

            handleClient(newDataSocket);                                //Call handleClient method
        }   

Aus der handleClient-Methode ... (in einer Schleife, die die Anforderungsmethode und den Pfad analysiert)

                    if(checkURL.compareTo("/status") == 0)  {   // Check to see if status page has been requested
                    System.out.println("STATUS PAGE");      // TEMPORARY. JUST TO MAKE SURE WE ARE PROPERLY ACCESSING STATUS PAGE
                    sendFile("/status.html", dataStream);
                }
                else {
                    sendFile(checkURL, dataStream);         // If not status, just try the input as a file name
                }

Von der sendFile-Methode ...

        File f = new File(where);                                               // Create the file object
    if(f.exists() == true) {                                                        // Test if the file even exists so we can handle a 404 if not.
        DataInputStream din;
        try {
            din = new DataInputStream(new FileInputStream(f));
            int len = (int) f.length();                                     // Gets length of file in bytes
            byte[] buf = new byte[len];
            din.readFully(buf);
            writer.write("HTTP/1.1 200 OK\r\n");                            // Return status code for OK (200)
            writer.write("Content-Length: " + len + "\r\n");                // WAS WRITING TO THE WRONG STREAM BEFORE!
            writer.write("Content-Type: "+type+"\r\n\r\n\r\n");             // TODO VERIFY NEW CONTENT-TYPE CODE
            out.write(buf);                                                 // Writes the FILE contents to the client
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();                                            // Not really handled since that's not part of project spec, strictly for debug.
        }
    }
    else {
        writer.write("HTTP/1.1 404 Not Found\r\n");                         // Attempting to handle 404 as simple as possible.
        writer.write("Content-Type: text/html\r\n\r\n\r\n");
        sendFile("/404.html", sock);
    }

Kann jemand erklären, wie ich in der Bedingung von sendFile die Antwort im 404-Block ändern kann (Wie ich bereits sagte, zeigen die Antwort-Header immer noch 200 OK an)? Das nervt mich, und ich möchte nur die HTTPResponse-Klasse verwenden, kann es aber nicht. (Außerdem werden Länge und Typ des Inhalts nicht angezeigt, wenn f.exists == true ist.)

Vielen Dank

Antworten auf die Frage(6)

Ihre Antwort auf die Frage