1

Hello all, I have created a web server in Java. It serves files from a directory. It is working fine, everything is good, except when I try to access files which have images in them, it does not load them up.

Here is the code.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Main {

    /**
     * @param args
     * @throws Exception 
     */
    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub

         new Main().runserver();






    }

     ServerSocket serverSocket;





    public void runserver() throws Exception {


        serverSocket = new ServerSocket(8080);
        acceptRequest();

    }

    private void acceptRequest() throws Exception{

        while(true){

            Socket s = serverSocket.accept();

            ConnectionHandler ch = new ConnectionHandler(s);
            ch.start();
        }

    }


       public class ConnectionHandler extends Thread {

           PrintWriter pw;
           BufferedReader br;

           Socket s;
           public ConnectionHandler(Socket s) throws Exception{
               this.s = s;

               br = new BufferedReader(new InputStreamReader(s.getInputStream()));
               pw = new PrintWriter(s.getOutputStream()); 



           }

           @Override
        public void run() {
               try{

               String reqS = "";


               while (br.ready() || reqS.length() == 0){

                   reqS += (char) br.read();
        }

               System.out.println(reqS);

               HttpRequest req = new HttpRequest(reqS);
               HttpResponse res = new HttpResponse(req);


               pw.write(res.response.toCharArray());
               pw.close();
               br.close();
               s.close();


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


       }


       public class HttpRequest{
           public String filename ;

        public HttpRequest(String request){

               String lines[] = request.split("\n");
               lines = lines[0].split(" ");
               filename = lines[1];


           } 

       }
             public class HttpResponse{

                 HttpRequest req;

                 String root;

                 String response;

                 public HttpResponse(HttpRequest request){
                     req=request;

                     root = "D:/";

                     File f  = new File(root + req.filename);


                     try{


                     response+= "HTTP/1.1 200 \r\n";
                     response+= "Apache Server /1.0";
                     response+= "Content-Type: text/html \r\n";
                     response+="Connection: close \r\n";
                     response+= "Content-Length:" + f.length() + "\r\n";
                     response+= "\r\n";

                     FileInputStream fis = new FileInputStream(f);


                     int s;

                     while ((s = fis.read()) != -1){

                         response += (char)s ;


                     }

                     fis.close(); 



                 }catch(FileNotFoundException fg){
                     response = response.replace("200", "404");

                 }

                     catch(IOException e ){

                         response  = response.replace("200", "500");

                         e.printStackTrace();
                     }
             }




}

}
Prakhar
  • 2,270
  • 19
  • 26

1 Answers1

3

You're explicitly setting the Content Type to text/html for every item:

response+= "Content-Type: text/html \r\n";

This will work fine for content which is text and/or HTML, but for anything else (such as images) it will confuse the web browser. You're basically telling the web browser to treat the image's raw data as text. It's trying to comply with this, but naturally it's unable to do so.

Your web server is going to have to determine the file type and use the correct Content Type for that file when building the HTTP response.

David
  • 208,112
  • 36
  • 198
  • 279
  • ok can you give me code snippet for checking file type and making correct response or please can you tell me how to use nanohttpd in a activity. thanx for answereing will upvote. – Prakhar Jul 20 '13 at 16:13
  • @user2589896: I can't give you completed code, no. However, a quick Google search for "java get content type for file" led me to a related question with very helpful information on that: http://stackoverflow.com/questions/51438/getting-a-files-mime-type-in-java – David Jul 20 '13 at 16:20
  • hey can you tell me how to use nanohttpd in a activity please. – Prakhar Jul 20 '13 at 16:23
  • @user2589896: I don't know what "nanohttpd" is, nor do I know what you mean by "activity" in this context. I do, however, know that a web server needs to send the correct Content Type to the client when sending a response. – David Jul 20 '13 at 16:25
  • ok no problem.. and please upvote my question if you want because i want to join chat room but i cant because i have 15 reputation and need 5 more. – Prakhar Jul 20 '13 at 16:27
  • sir please have a look at http://stackoverflow.com/questions/18055743/android-webserver-shows-html-pages-as-text – Prakhar Aug 05 '13 at 13:19