我試圖讓託管在我們的服務器上的圖像可以顯示在客戶端上。按照該項目的規格:如何通過HttpURLConnection傳遞文件
「當客戶收到這樣一個URL,它必須下載 內容(即字節)由URL引用的文件 之前的客戶端可以顯示圖像的。用戶,必須首先檢索(即下載)從服務器 圖像文件的字節。同樣,如果客戶端接收已知的數據文件,或從服務器領域幫助文件 的URL,它必須下載這些文件的內容纔可以使用它們。「
我敢肯定,我們在服務器端的東西了,因爲如果我把網址到瀏覽器中它檢索和顯示就好了。所以它必須是ClientCommunicator類的東西;你能看看我的代碼並告訴我問題是什麼嗎?我花了幾個小時。
下面是代碼:
當我實際調用該函數來獲取和顯示文件:(這部分工作正常,因爲它是傳遞正確的信息到服務器)
JFrame f = new JFrame();
JButton b = (JButton)e.getSource();
ImageIcon image = new ImageIcon(ClientCommunicator.DownloadFile(HOST, PORT, b.getLabel()));
JLabel l = new JLabel(image);
f.add(l);
f.pack();
f.setVisible(true);
從ClientCommunicator類:
public static byte[] DownloadFile(String hostname, String port, String url){
String image = HttpClientHelper.doGetRequest("http://"+hostname+":"+port+"/"+url, null);
return image.getBytes();
}
相關httpHelper:
public static String doGetRequest(String urlString,Map<String,String> headers){
URL url;
HttpURLConnection connection = null;
try {
//Create connection
url = new URL(urlString);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
if(connection.getResponseCode() == 500){
return "failed";
}
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
}
之後,它一躍而起服務器上的東西,這正如我所說,我相信工作正常,因爲客戶端,如Chrome瀏覽器可以檢索該文件並正確顯示。問題必須在這裏的某個地方。
我認爲,它與字節轉換成字符串,然後回來的路上做的,但我不知道如何解決這個問題。我查看了StackOverflow中的類似問題,但無法將它們應用於我的情況。任何正確的方向指針將不勝感激。
我最終創建了另一個名爲doByteGetRequest的doGetRequest版本,它使用了ByteArrayOutputStream而不是像我發佈的方法那樣使用outputStream,並直接寫入字節而不是使用讀取器。這似乎奏效了。謝謝! –