Search code examples
javahtmlsocketsrequestserversocket

Sending HTTP request's


I am writing a web client. I have the following code.

public class Connection extends Thread{
public final static int PORT = 1337;
private ServerSocket svrSocket = null;
private Socket con  =  null;
public Connection(){

    try{
        svrSocket = new ServerSocket(PORT);
        System.out.println("Conected to: " + PORT);

    }catch(IOException ex)
    {
       System.err.println(ex);
       System.out.println("Unable to attach to port");
   }

}

public void run(){

while(true)
{

        try{
            con = svrSocket.accept();//on this part the program stops
            System.out.println("Client request accepted");
            PrintWriter out = new PrintWriter(con.getOutputStream());
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            out.println("GET /<index.html> HTTP/1.1");

            out.println("***CLOSE***");
            System.out.println(in.readLine());
           /*
            String s;

            while((s = in.readLine()) != null)
            {
                System.out.println(s);
            }*/
            out.flush();
            out.close();
            in.close();
            con.close();

            System.out.println("all closed");
    }
        catch(IOException ex)
    {
        ex.printStackTrace();

    }



}
}

}

The run method will be used latter on. That I have is a file called index.html. This file is in the same file as the java code. What I am trying to do with the request is send the HTML file. But if I run this program on a web browser localhost:1337 the following gets displayed.

GET /<index.html> HTTP/1.1
***CLOSE***

This should not get displayed. The page that results of the HTML code in the index.html should get displayed.

Index.html code:

<html>
 <head>
  <title>       </title>

 </head>
 <body bgcolor = "#ffffcc" text = "#000000">
  <h1>Hello</h1>
  <p>This is a simple web page</p>
 </body>
</html>

How do I get this html page to display in the browser?

Thank you


Solution

  • t seems that all is good on your code, it seems you need to read the HTTP header from the input stream so you can get the requested file name and then use the Socket output stream to write the response from the file.

    OutputStream output = con.getOutputStream();
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String fileName = readHeader(in);
    String baseDir = System.getProperty("my.base.dir", "/home/myname/httpserver");
    boolean exist = true;
    InputStream fileIn = null;
    try {
       File requestedFile = new File(baseDir, fileName);
       fileIn = new FileInputStream(requestedFile);
    } catch(Exception e){
        exist = false;
    }
    
    String server = "Java Http Server";
    String statusLine = null;
    String typeLine = null;
    String body = null;
    String lengthLine = "error";
    
    if (exist) {
       statusLine = "HTTP/1.0 200 OK" + "\r\n";
       //get content type by extension
       typeLine = "Content-type: html/text  \r\n";
       lengthLine = "Content-Length: " + (new Integer(fileIn.available())).toString() + "\r\n";
    } else {
      statusLine = "HTTP/1.0 404 Not Found" + CRLF;
      typeLine = "text/html";
      body = "<HTML>" + "<HEAD><TITLE>404</TITLE></HEAD>" + "<BODY>404 Not Found"+"</BODY></HTML>";
    }
    
    output.write(statusLine.getBytes());
    output.write(server.getBytes());
    output.write(typeLine.getBytes());
    output.write(lengthLine.getBytes());
    
    output.write("\r\n".getBytes());
    
    if (exist) {
       byte[] buffer = new byte[1024];
       int bytes = 0;
    
       while ((bytes = fileIn.read(buffer)) != -1) {
         output.write(buffer, 0, bytes);
       }
    } else {
       output.write(body.getBytes());
    }
    //close sreams