2011-04-07 38 views
0

下面是一個示例代碼,我用它來訪問一個示例jpg文件,但是在連接之後,我看不到文件的長度,也沒有下載到SD卡上的文件!(不是accessign HTTP連接和HTTPS連接是否一樣?)存儲在HTTPS服務器上的圖像,如何檢索它們?

以下是我使用的示例代碼。 URL = 「https://calomel.org/calomel_footer.jpg」

private Bitmap getImageBitmap(String url) { 
    Bitmap bm = null; 
    try { 
     URL aURL = new URL(url); 
     URLConnection conn = aURL.openConnection(); 
     Log.i("My_App", "Content Type = "+URLConnection.guessContentTypeFromName(url)); 
     conn.connect(); 
     Log.i("My_App", "Content Length = "+conn.getContentLength()); 
     Log.i("My_App", "Content Type = "+conn.getContentType()); 
     FileOutputStream fos = new FileOutputStream(new File("/mnt/sdcard/calomel_footer.jpg")); 
     InputStream is = conn.getInputStream(); 
     byte buf[]=new byte[1024]; 
     int len; 
     while((len=is.read(buf))>0) { 
      fos.write(buf,0,len); 
     } 
     fos.close(); 
     BufferedInputStream bis = new BufferedInputStream(is); 
     bm = BitmapFactory.decodeStream(bis); 
     bis.close(); 
     is.close(); 

    } catch (Exception e) { 
     Log.e("My_App", "Error getting bitmap", e); 
    } 
    return bm; 
} 

,我也得到顯示爲-1和內容類型2爲空的lenght。

另外,當我看到我的文件存儲在「/mnt/sdcard/calomel_footer.jpg」下時,我看到0字節的文件。

任何人都可以幫我解決這個問題嗎?

回答

0

getContentType()中的null是因爲網絡服務器沒有提供合適的標題。從getContentLength() -1是因爲再次網絡服務器沒有提供一個合適的頭,併發送它在塊編碼。

在這些情況下,只有通過實際下載文件並查看有多少字節才能發現長度。

+0

我得到0字節的文件當我下載 – Sana 2011-04-07 21:30:43

0

首先,圖片在https://calomel.org/calomel_footer.jpg不爲我加載。我看到一條消息說[圖片「https://calomel.org/calomel_footer.jpg」無法顯示,因爲它包含錯誤。]。

其次,您從Web服務器獲取輸入流,並通過文件輸出流寫入輸入流。 完成之後,您正嘗試再次讀取相同的Web服務器輸入流(您通過BitmapFactory執行的操作)。這些流只有一次很好。你想要做的是一樣的東西:

while((len=is.read(buf))>0) { 
     fos.write(buf,0,len); 
    } 
    fos.close(); 
    FileInputStream fis = new FileInputStream(myFile); // myFile is the File that you wrote the FileOutputStream to. 
    BufferedInputStream bis = new BufferedInputStream(fis); 
    bm = BitmapFactory.decodeStream(bis); 
+0

我覺得我的代碼做了兩個部分,一部分一次存儲文件,另一部分送位圖對象。它可以在http服務器上工作......我的意思是它對於HTTP連接來說工作得很好。 – Sana 2011-04-07 21:53:42

相關問題