[英]Android AsyncTask, handle unavailable server
我正在使用本教程: http : //hmkcode.com/android-parsing-json-data/從虛擬機上的服務器獲取JSON數據。 服務器打開時,它工作正常,但服務器不可用時,我的應用程序崩潰。 我應該如何處理這種情況?
按下按鈕后,我執行:
httpAsyncTask.execute("http://localhost:3000"); //changed on purpose, it works with given IP
httpAsyncTask類:
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
return GET(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Worked fine", Toast.LENGTH_LONG).show();
goToMyActivity();
}
}
在調試中,我的應用程序停止在:
HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
int GET方法:
public static String GET(String url){
InputStream inputStream = null;
String result = "";
try {
// create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// make GET request to the given URL
HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// convert inputstream to string
if (inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e){
Log.e("Http:",e.toString());
}
return result;
}
捕獲的異常為空。
使用getResponseCode();
HttpURLConnection
類以確保成功建立連接。
getResponseCode();
如果連接成功,將返回200
。
int responseCode = -1;
feedURL = "your URL"
HttpURLConnection connection;
connection = (HttpURLConnection) feedURL.openConnection();
connection.connect();
responseCode = connection.getResponseCode();
然后使用if
塊檢查connection.getResponseCode()
是否返回200
。 可以使用常量HttpURLConnection.HTTP_OK
代替硬編碼200
。
if (responseCode == HttpURLConnection.HTTP_OK) {
// do your stuff here
}
else {
// Show some error dialog or Toast message
}
使用catch塊來捕獲超時異常(及其他):
String message = "";
try {
//HTTP stuff here
if (responseCode == HttpURLConnection.HTTP_OK) {
// do your stuff here
} else {
// Show some error dialog or Toast message
}
} catch (Exception e) {
message = e.getLocalizedMessage();
e.printStackTrace();
}
// Toast message
如果超時,此函數將返回null,否則將發送響應
公共靜態字符串Get(字符串url){
// Create a new HttpClient HttpParams params = new BasicHttpParams(); // set your timeouts here HttpConnectionParams.setConnectionTimeout(params, 5000); HttpConnectionParams.setSoTimeout(params, 10000); HttpClient httpclient = new DefaultHttpClient(params); try { // Execute HTTP GET Request HttpResponse response = httpclient.execute(new HttpGet(url)); return EntityUtils.toString(response.getEntity()); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.