2011-10-31 51 views
0

我在使用JAVA編寫基本的網絡服務器時發生了一些麻煩。目前它在傳遞html或css文件方面工作良好。但是當涉及到圖像時,事情就會變得混亂起來。我假設我在閱讀圖像文件並準備發送它時做錯了什麼。但在代碼看看:如何創建一個在JAVA中發送圖像的HTTP響應?

public void launch() 
{ 
    while(true) 
    { 
     try 
     { 
      Socket connection = this.server_socket.accept(); 

      ... 

      PrintWriter print_writer = new PrintWriter(connection.getOutputStream()); 

      String response = this.readFile(this.request_header.get("Resource")); 
      print_writer.print(response); 

      print_writer.flush(); 
      connection.close(); 
     } 
     catch(...) 
     { 
      ... 
     } 
    } 
} 

private String readFile(String path) 
{ 
    try 
    { 
     ... 

     FileInputStream file_input_stream = new FileInputStream(path);   
     int bytes = file_input_stream.available(); 
     byte[] response_body = new byte[bytes]; 

     file_input_stream.read(response_body); 
     this.response_body = new String(response_body); 

     file_input_stream.close(); 

     this.setResponseHeader(200, file_ext); 

     this.response_header = this.response_header + "\r\n\r\n" + this.response_body; 
    } 
    catch(...) 
    { 
     ... 
    } 

    return this.response_header; 
} 

所以,我的瀏覽器會收到類似:

HTTP/1.0 200 OK 
Content-type: image/jpeg 

[String that was read in readFile()] 

但Chrome的無法正確顯示圖像和歌劇不會出現這一切!我曾經用BufferedReader讀取文件,但我發現有人說BufferedReader無法正確處理二進制數據,所以我嘗試使用FileInputStream,但問題保持不變):

感謝您的任何提示和幫助提前(:

回答

2

您必須在兩邊使用流:輸入流和輸出流讀者和作者假設內容是Unicode並對字節流進行調整PrintWriter當然是一個作家

相關問題