2014-01-18 45 views
0

在我的應用程序中,我發送多個http請求。 因爲,網絡可能隨時停機。那麼,在發送每個請求之前,我應該使用android ConnectionManager來檢查網絡狀態?我覺得還有其他更好的方法可以處理這個問題(每次在每個片段上發送多個請求時,不要使用android連接管理器服務)處理會話,網絡狀態和http請求

回答

2

請看this question.如果您想避免使用ConnectionManager,您可以使用try-catch塊並在嘗試建立連接時檢查異常(前提是您使用java.net.*庫來執行HTTP請求)。例如,在這個問題中使用了類似的東西:

URL url = ... 

HttpURLConnection c = (HttpURLConnection) url.openConnection(); 
c.setReadTimeout(15000); 

try { 
    InputStream in = new BufferedInputStream(c.getInputStream()); 
    httpResult = readStream(in); 
} catch (IOException e) { 

    // Here is where an exception would be thrown if there is no internet. 
    // Would likely actually be an UnknownHostException 

    Log.e(TAG, "Error: ", e); 

} finally { 
    c.disconnect(); 
}