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

时间:2015-01-11 12:27:06

标签: java android android-asynctask

我正在使用本教程: 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;
}

捕获的异常为空。

3 个答案:

答案 0 :(得分:1)

使用getResponseCode();类的HttpURLConnection来确保连接成功建立。

如果连接成功,

getResponseCode();将返回200

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

然后使用if块检查200是否返回connection.getResponseCode()。 可以使用常量HttpURLConnection.HTTP_OK代替硬编码200

                if (responseCode == HttpURLConnection.HTTP_OK) {
                      // do your stuff here
                }
                else { 
                     // Show some error dialog or Toast message
                }

答案 1 :(得分:0)

使用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

答案 2 :(得分:0)

如果超时,此函数将返回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;
     

}