我正在尋找處理HttpURLConnection中的錯誤的最佳實踐,尤其是在主機不可用時。我怎麼不得不改變我的源?:在AsyncTask中捕獲HttpUrlConnection的錯誤
protected String doInBackground(String... strings) {
URL aURL;
String line;
HttpURLConnection connection;
BufferedReader reader;
StringBuilder stringBuilder = null;
try {
aURL = new URL(strings[0]);
connection = (HttpURLConnection) aURL.openConnection();
InputStream aInputStream = connection.getInputStream();
BufferedInputStream aBufferedInputStream = new BufferedInputStream(aInputStream);
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
stringBuilder = new StringBuilder();
while ((line = reader.readLine()) != null)
{
stringBuilder.append(line);
}
} catch (IOException e) {
Log.d("svc", e.toString());
}
return stringBuilder.toString();
}
那麼,例外被捕獲 - 你想*發生什麼? – 2013-02-06 19:12:07
既然你最初沒有分配'stringBuilder',如果你有一個異常,那麼你將有麻煩'返回stringBuilder.toString();'(NullPointerException,我認爲) –
嗨,我想返回結果 - 好的,我可以通過返回語句來做到這一點,但對我來說更重要的是:如何捕獲由連接拋出的異常(connection =(HttpURLConnection)aURL.openConnection();),或者是一個catch塊足夠做這個? – fillibuster