Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7529099
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T04:34:03+00:00 2026-05-30T04:34:03+00:00

I wrote this HttpRequest method, but for some reason it always goes to 404

  • 0

I wrote this HttpRequest method, but for some reason it always goes to 404 Not Found, even though the file location exists when the java process isn’t running.

import java.io.*;
import java.net.*;
import java.util.*;

final class HttpRequest implements Runnable {
    final static String CRLF = "\r\n";
    Socket socket;

    // Constructor
    public HttpRequest(Socket socket) throws Exception {
        this.socket = socket;
    }

    // Implement the run() method of the Runnable interface.
    public void run() {
        try {
            processRequest();
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    private static void sendBytes(FileInputStream fis, OutputStream os) 
    throws Exception {
    // Construct a 1K buffer to hold bytes on their way to the socket.
    byte[] buffer = new byte[1024];
    int bytes = 0;

    // Copy requested file into the socket's output stream.
    while((bytes = fis.read(buffer)) != -1 ) {
        os.write(buffer, 0, bytes);
        }
    }

    private static String contentType(String fileName) {
    if(fileName.endsWith(".htm") || fileName.endsWith(".html")) {
        return "text/html";
    }
    if(fileName.endsWith(".jpeg") || fileName.endsWith(".jpg")) {
    return "image/jpeg";
    }
    if(fileName.endsWith(".gif")) {
    return "image/gif";
    }
    return "application/octet-stream";
    }

    private void processRequest() throws Exception {
        // Get a reference to the socket's input and output streams.
        InputStream is = socket.getInputStream();
        DataOutputStream os = new DataOutputStream(socket.getOutputStream());

        // Set up input stream filters.
        BufferedReader br = new BufferedReader(new InputStreamReader(is));

        // Get the request line of the HTTP request message.
        String requestLine = new String(br.readLine());

        // Display the request line.
        System.out.println();
        System.out.println(requestLine);

        // Get and display the header lines.
        String headerLine = null;
        while ((headerLine = br.readLine()).length() != 0) {
            System.out.println(headerLine);
        }

    // Extract the filename from the request line.
    StringTokenizer tokens = new StringTokenizer(requestLine);
    tokens.nextToken(); // skip over the method, which should be "GET"
    String fileName = tokens.nextToken();
    // Prepend a "." so that file request is within the current directory.
    fileName = "." + fileName;

    // Open the requested file.
    FileInputStream fis = null;
    boolean fileExists = true;
    try {
    fis = new FileInputStream(fileName);
    } catch (FileNotFoundException e) {
    fileExists = false;
    }

    // Construct the response message.
    String statusLine = null;
    String contentTypeLine = null;
    String entityBody = null;
    if (fileExists) {
    statusLine = "200 OK" + CRLF;
    contentTypeLine = "Content-type: " + 
        contentType( fileName ) + CRLF;
    } else {
    statusLine = "404 NOT FOUND" + CRLF;
    contentTypeLine = "Content Not Found!" + CRLF;
    entityBody = "<HTML>" + 
        "<HEAD><TITLE>Not Found</TITLE></HEAD>" +
        "<BODY>Not Found</BODY></HTML>";
    }

    // Send the status line.
    os.writeBytes(statusLine);

    // Send the content type line.
    os.writeBytes(contentTypeLine);

    // Send a blank line to indicate the end of the header lines.
    os.writeBytes(CRLF);

    // Send the entity body.
    if (fileExists) {
    sendBytes(fis, os);
    fis.close();
    } else {
    os.writeBytes("File DNE: Content Not Found!");
    }

        // Close streams and socket.
        os.close();
        br.close();
        socket.close();
    }
}

Any help would be greatly appreciated…I feel like it’s something simple I’m missing.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T04:34:05+00:00Added an answer on May 30, 2026 at 4:34 am

    I ran your code; it works fine (except for some minor issues with not printing the headers correctly, which every browser I’ve tried is willing to completely ignore).

    Are you sure your working directory is where you expect? Try changing the 404 message to something like:

    contentTypeLine = "Content Not Found: " + new File(fileName).getAbsolutePath() + CRLF;
    

    For reference, I ran it with a test harness of:

    public static void main(String[] args) throws Exception {
            final ServerSocket ss = new ServerSocket(8080);
            while (true)
                new HttpRequest(ss.accept()).run();
        }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I wrote this method to check if a page exists or not: protected bool
I wrote this snippet of code and I assume len is tail-recursive, but a
I wrote this script which counts occurrences of particular pattern in a given file.
I wrote this ISAPI filter to rewrite the URL because we had some sites
I found many posts when I queried for this problem, but they all refer
I wrote this function that's supposed to do StringPadRight("Hello", 10, "0") -> "Hello00000" .
I wrote this code I have these errors Cannot implicitly convert type x.Program.TreeNode' to
I wrote this function for filling closed loop, pixvali is declared globally to store
I wrote this function to get the unread count of google reader items. function
I wrote this function to get a pseudo random float between 0 .. 1

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.