构建Java HTTP服务器的http头

时间:2014-01-02 18:11:38

标签: java http webserver

我正在尝试创建一个简单的HTTP服务器来处理来自浏览器的请求并返回相应的答案。我已经实现了基本连接,但是我无法正确构建返回标头,因此浏览器可以显示服务器的答案(例如从服务器获取.jpg图片并正确显示)。

我认为我遇到的问题与正确构建答案标题有关。我对这方面的经验不多,我将不胜感激。

下面是我的HttpHandler类,它处理来自浏览器的请求并返回答案。我认为这个问题出现在httpHeaderConstructor方法中。

  package Server;

    import java.io.BufferedReader;
    import java.io.DataOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import org.apache.commons.io.FilenameUtils;

    public class HttpHandler {

        public static void httpHandler(BufferedReader clientInput, DataOutputStream serverResponse){ 

            int type_of_method = 0; 

            String path = new String();

            try{

                String tmp = clientInput.readLine(); 
                String tmp2 = new String(tmp);

                tmp.toUpperCase();

                System.out.println("Clients request call:" + tmp);

                if(tmp.startsWith("GET"))
                    type_of_method = 1;

                if(type_of_method == 0){ 
                    try{
                        serverResponse.writeBytes(httpHeaderConstructor(501, 0));
                        serverResponse.close();
                        return;

                    }catch(Exception e){
                        System.out.println("1.Error: " + e.getMessage());
                    }
                }

                int start = 0;
                int end = 0;

                for(int a = 0; a < tmp2.length(); a++){
                    if(tmp2.charAt(a) == ' ' && start != 0){
                        end = a;
                        break;
                    }
                    if(tmp2.charAt(a) == ' ' && start == 0){
                        start = a;
                    }       
                }

                path = tmp2.substring(start + 2, end); 
                System.out.println("Requested file path: " + path);

            }catch(Exception e){
                System.out.println("2.Error (bad request Exception): " + e.getMessage());
            }

            System.out.println("Client requested: " + new File(path).getAbsolutePath());

            sendRequestedFile(path, serverResponse);

        }

        private static void sendRequestedFile(String filePath, DataOutputStream srvResponse){

            FileInputStream requestedFile = null;

            try{

                requestedFile = new FileInputStream(filePath); 
                System.out.println("File found and opened successfully");

            }catch(Exception e){

                try {

                    System.out.println("Could not find file!");
                    srvResponse.writeBytes(httpHeaderConstructor(404, 0));
                    srvResponse.close();

                } catch (Exception err) {
                    System.out.print("Error: Can't send failed response!");
                    System.out.print("Error message: " + err.getMessage());

                }   
            }

            String fileExtension = "." + FilenameUtils.getExtension(filePath); 

            int fileType = 0;

            if(fileExtension.equalsIgnoreCase(".jpg") || fileExtension.equals(".jpeg"))
                fileType = 1;

            if(fileExtension.equals(".gif"))
                fileType = 2;

            if(fileExtension.equals(".zip"))
                fileType = 3;   

            try {
                srvResponse.writeBytes(httpHeaderConstructor(200, fileType));
                srvResponse.close();
                requestedFile.close();

            } catch (Exception e) {
                System.out.println("Error message: " + e.getMessage());
            }

        }

        private static String httpHeaderConstructor(int returnCode, int typeOfFile){ 

            String s = "HTTP/1.0"; 

            switch (returnCode) { 
            case 200:
                s += "200 OK";
                break;

            case 400:
                s += "400 Bad Request";
                break;

            case 403:
                s += "403 Forbidden";
                break;

            case 404:
                s += "404 File not found";
                break;

            case 500:
                s += "500 Internal server error";
                break;

            case 501:
                s += "501 Not implemented";
                break;
            }

            s = s + "\r\n";
            s = s + "Connection: closing...\r\n";
            s = s + "Server: Java HTTP Server v0.1\r\n";


            switch (typeOfFile) {
            case 0:
                break;

            case 1:
                s = s + "Content-Type: image/jpeg\r\n";
                break;
            case 2:
                s = s + "Content-Type: image/gif\r\n";
                break;
            case 3:
                s = s + "Content-Type: application/x-zip-compressed\r\n";
                break;
            default:
                s = s + "Content-Type: text/html\r\n";
                break;
            }

            s = s + "\r\n";

            System.out.println("The returning header is: " + s);

            return s;

        }
    }

这是程序正在构建的标题:

HTTP/1.0 200 OK
Connection: close
Server: Java HTTP Server v0.1
Content-Type: image/jpeg

这些是浏览器中显示的HTML标记:

<html>

    <head></head>
    <body>
        <img src="http://localhost:6565/Moon.jpg" alt="The image “http://localhost:6565/Moon.jpg” cannot be displayed because it contains errors."></img>
    </body>

</html>

当您尝试获取.jpeg图像时会发生这种情况。

1 个答案:

答案 0 :(得分:0)

首先,请考虑here

中的此示例响应标头
HTTP/1.1 200 OK
Date: Mon, 23 May 2005 22:38:34 GMT
Server: Apache/1.3.3.7 (Unix) (Red-Hat/Linux)
Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT
ETag: "3f80f-1b6-3e1cb03b"
Content-Type: text/html; charset=UTF-8
Content-Length: 131
Connection: close

其次,更改您的功能httpHeaderConstructor

 private static String httpHeaderConstructor(
    int returnCode, int typeOfFile) {
  // You should use a StringBuilder.
  StringBuilder sb = new StringBuilder("HTTP/1.0 "); // <--
                                                     // Missed
                                                     // space.
  switch (returnCode) {
  case 200:
    sb.append("200 OK");
    break;
  case 400:
    sb.append("400 Bad Request");
    break;
  case 403:
    sb.append("403 Forbidden");
    break;
  case 404:
    sb.append("404 File not found");
    break;
  case 500:
    sb.append("500 Internal server error");
    break;
  case 501:
    sb.append("501 Not implemented");
    break;
  }

  sb.append("\r\n");
  sb.append("Connection: close\r\n"); // <-- Not closing
  sb.append("Server: Java HTTP Server v0.1\r\n");

  switch (typeOfFile) {
  // case 0: // <-- Not a good idea.
  //  break;
  case 1:
    sb.append("Content-Type: image/jpeg\r\n");
    break;
  case 2:
    sb.append("Content-Type: image/gif\r\n");
    break;
  case 3:
    sb.append(
        "Content-Type: application/x-zip-compressed\r\n");
    break;
  default:
    sb.append("Content-Type: text/html\r\n");
    break;
  }

  sb.append("\r\n");
  System.out.println("The returning header is: " + sb.toString());
  return sb.toString();
}