2014-09-19 32 views
0

我相當堅持爲我必須區分Url.openStream()期間發生的常見HTTP錯誤。主要目的是確定下面的HTTP Get請求錯誤:Diffientiate URL.openStream中的常見Http錯誤()

  1. 400(壞請求)
  2. 401(未授權)
  3. 403(禁止)
  4. 404(未找到)
  5. 500(內部服務器錯誤)

到目前爲止,我只能通過捕獲FileNotFoundException來識別404。這是我的代碼片段:

try { 
    file.createNewFile(); 
    URL url = new URL(fileUrl); 
    URLConnection connection = url.openConnection(); 
    connection.connect(); 

    // download the file 
    InputStream input = new BufferedInputStream(url.openStream()); 

    // store the file 
    OutputStream output = new FileOutputStream(file); 

    byte data[] = new byte[1024]; 
    int count; 
    while ((count = input.read(data)) != -1) { 
     output.write(data, 0, count); 
     Log.e(TAG, "Writing"); 
    } 

    output.flush(); 
    output.close(); 
    input.close(); 
    result = HTTP_SUCCESS; 
} catch (FileNotFoundException fnfe) { 
    Log.e(TAG, "Exception found FileNotFoundException=" + fnfe); 
    Log.e(TAG, "FILE NOT FOUND"); 
    result = HTTP_FILE_NOT_FOUND; 
} catch (Exception e) { 
    Log.e(TAG, "Exception found=" + e); 
    Log.e(TAG, e.getMessage()); 
    Log.e(TAG, "NETWORK_FAILURE"); 
    result = NETWORK_FAILURE; 
} 

這可能是一個小問題,但我完全無能。任何人都可以幫助請

回答

2

如果您使用HTTP投你的連接使用connection.getResponseCode()HttpUrlConnection之前打開的流檢查響應狀態代碼:

connection = (HttpURLConnection) new URL(url).openConnection(); 
/* ... */ 
final int responseCode = connection.getResponseCode(); 
switch (responseCode) { 
    case 404: 
    /* ... */ 
    case 200: { 
    InputStream input = new BufferedInputStream(url.openStream()); 
    /* ... */ 
    } 
} 

而且不要忘記在finally塊密切的聯繫。

+0

Thanx ..它的工作:) – 2014-09-19 13:36:37