如果服务器因超时而关闭,则应用程序崩溃。我该怎么抓住它?

时间:2013-09-14 09:03:08

标签: android tomcat connection timeout httpurlconnection

            String urlStr = "nana.com/nana/api/v1"
            HttpURLConnection conn = null;
    BufferedReader rd = null;
    StringBuilder sb = null;
    try {
        URL url = new URL(urlStr);
        conn = (HttpURLConnection) url.openConnection();

        if (conn.getResponseCode() != 200) {
            throw new IOException(conn.getResponseMessage());
        }
        else {

        rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        sb = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            sb.append(line);
        } 
        rd.close();

        conn.disconnect();
        }
    } catch (IOException i) {
        i.printStackTrace();
                    }catch (Exception e) {
        e.printStackTrace();

如果服务器处于活动状态且工作正常,此代码适用于我,但当我关闭服务器时,它会进入超时状态并“意外崩溃”。我想要的只是如果服务器无法访问则应用程序说出或显示alertdialog。 这是我的logcat:

              09-14 11:52:57.702: E/AndroidRuntime(17256):  at android.os.Handler.dispatchMessage(Handler.java:99)
              09-14 11:52:57.702: E/AndroidRuntime(17256):  at                                     android.os.Looper.loop(Looper.java:130)
              09-14 11:52:57.702: E/AndroidRuntime(17256):  at android.app.ActivityThread.main(ActivityThread.java:3693)
              09-14 11:52:57.702: E/AndroidRuntime(17256):  at java.lang.reflect.Method.invokeNative(Native Method)
              09-14 11:52:57.702: E/AndroidRuntime(17256):  at java.lang.reflect.Method.invoke(Method.java:507)
              09-14 11:52:57.702: E/AndroidRuntime(17256):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907)
              09-14 11:52:57.702: E/AndroidRuntime(17256):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665)
              09-14 11:52:57.702: E/AndroidRuntime(17256):  at dalvik.system.NativeStart.main(Native Method)
              09-14 11:52:57.742: E/(179): Dumpstate > /data/log/dumpstate_app_error

1 个答案:

答案 0 :(得分:0)

请尝试以下

public String getData(String url) {

    HttpClient httpclient = new DefaultHttpClient(SetHttpParams.setHttp(
            50000, 50000));

    HttpGet httpget = new HttpGet(url);
    HttpResponse response;

    try {
        response = httpclient.execute(httpget);
        if (response.getStatusLine().getStatusCode() == 200) {
            org.apache.http.HttpEntity entity = response.getEntity();
            if (entity != null) {

                InputStream instream = entity.getContent();

                String res = Functions.convertStreamToString(instream);
            }
        }
    } catch (ConnectTimeoutException e) {
    } catch (SocketTimeoutException e) {
    } catch (IOException ex) {
    }
}

String res是存储响应的字符串。在Asyntasks doinBackground()方法中调用上面的函数。放置一些局部布尔变量来检查是否发生了异常。并且在onPostExecute()中显示对话框,如果发生异常或继续工作。 希望它可以帮到你。