2017-03-08 52 views
2

我有這個簡單的HTML,當我在Chrome中加載它時加載了我想要的。當通過套接字java發送HTML頁面時不會加載圖像

<body> 
    <div><h1>Welcome to my webpage!</h1></div> 
    <div>This page is being hosted on the local machine.</div> 
    <div>Now, here's a picture of a cat. Please enjoy.</div> 
    <img src="cat.jpg" alt="Business Cat" width="800" height="600"/> 
</body> 

當我通過Java中的套接字傳遞它時,我總是得到一個破損的圖像。我無法弄清楚爲什麼,因爲我只是通過套接字傳遞字節。

File index = new File("index.html"); 

byte[] bytes = new byte[16 * 1024]; 

InputStream in = new FileInputStream(index); 

while (true) 
{ 
    int read = in.read(bytes); 
    if (read < 0) 
     break; 
    out.write(bytes, 0, read); 
} 

out.flush(); 
out.close(); 

圖像文件「cat.jpg」與「index.html」位於同一個目錄中。我錯過了什麼?

回答

0

我認爲問題在於它發送另一個http請求。你應該提供例如:127.0.0.1/index.html來顯示你的index.html文件,而127.0.0.1/cat.jpg應該返回你的照片。 但我不確定你將如何解析java中的jpg文件。 但是,如果你在鉻,你去檢查;你去網絡。從那裏如果你重新加載,你會看到一個請求你的圖片或者正在等待,或者不是你返回的正確信息,這取決於你如何實現我們對http請求的處理。