简体   繁体   中英

Return content-type in java server

NOTE : just to be clear , i know how to do the if statements. I need a way of getting the actual content type and storing that in a variable as a string.

I have written a simple java server . I haven't figured out how to return the content type of the file the server loads.

I know it there would be an if statement that would set a string variable to for example text/html based on what another variable eg contetType is. So , for example :

if (contentType == ".html")
    {
        String s = "text/html";
    }
    else if ......

This is a section from the server (the code for an okay 200 response) :

         String okayreply="HTTP/1.0 200 OK \r\n" +
               "Connection: close\r\n" +
               "Content-Lenght : "+ file1.length() + 
               "Content-Type:" +
               "\r\n" +
               "\r\n" +
               "<h2>File Found</h2>\r\n";

    System.out.println(okayreply );

So I need to find the content type and store it in a variable . From that I can use that information to set the content type when the response message is displayed.

EDIT , It just returns blank for the content type:

File file1 = new File (filename);
String s = "";

  int indexOfFinalDot = filename.lastIndexOf(".");
if (indexOfFinalDot > 0) {
    String fileExtentsion = filename.substring(indexOfFinalDot).toLowerCase();
    if ("html".equals(fileExtentsion)) {
       s = "text/html";
    }
}

Also :

String okayreply="HTTP/1.0 200 OK \r\n" +
               "Connection: close\r\n" +
               "Content-Lenght : "+ file1.length() + "\r\n" +
               "Content-Type: " + s +
               "\r\n" +
               "\r\n" +
               "<h2>File Found</h2>\r\n";

    System.out.println(okayreply );

You can try to determine the content type of a file based on the file extension

Please note that the logic does try to guess the content type based on the filename. If the filename is wrong (no extension / wrong extension) the content-type header will most probably be wrong.

Assuming you have a file name somewhere:

    String filename = "index.html"; 

    int indexOfFinalDot = filename.lastIndexOf(".");
    if (indexOfFinalDot > 0) {
        String fileExtentsion = filename.substring(indexOfFinalDot + 1).toLowerCase();
        if ("html".equals(fileExtentsion)) {
           //your logic here
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM