Android AsyncTask,处理不可用的服务器

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 class:

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(); of HttpURLConnection class确保连接建立成功。

如果连接成功,

getResponseCode(); 将 return 200

                int responseCode = -1;
                feedURL = "your URL"
                HttpURLConnection connection;
                connection = (HttpURLConnection) feedURL.openConnection();
                connection.connect();
                responseCode = connection.getResponseCode();

然后使用 if 块来检查 200 是否由 connection.getResponseCode() 编辑 return。 可以使用常量 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

如果超时,此函数将return null 否则将发送响应

public static String Get(String 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;

}