Android Connection / SocketTimeOutException捕获应用程序仍然崩溃

时间:2013-01-17 06:02:28

标签: java android exception timeout httpresponse

基本上我试图让用户知道应用程序何时无法访问服务器/服务器,而他们的手机互联网/数据连接完全没问题。所以我按照这篇文章设置了超时:How to set HttpResponse timeout for Android in Java

它运行良好,除非正确捕获异常,应用程序仍会崩溃,而不是显示Toast消息并返回到应用程序屏幕。请注意“Log.e(”CONN TIMEOUT“,e.toString());”在logcat中正确记录为:“CONN TIMEOUT org.apache.http.conn.ConnectTimeoutException:Connect到/192.168.11.60:80超时“

根据要求,完整logcat:http://pastebin.com/rpe8iKRi

    // Making HTTP request
    try {

        HttpParams httpParameters = new BasicHttpParams();
        // Set the timeout in milliseconds until a connection is established.
        // The default value is zero, that means the timeout is not used. 
        int timeoutConnection = 3000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        // Set the default socket timeout (SO_TIMEOUT) 
        // in milliseconds which is the timeout for waiting for data.
        int timeoutSocket = 5000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params));

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (ConnectTimeoutException e) {
        Toast.makeText(getApplicationContext(), "Server timeout", Toast.LENGTH_LONG).show();
        Log.e("CONN TIMEOUT", e.toString());
    } catch (SocketTimeoutException e) {
        Toast.makeText(getApplicationContext(), "Server timeout", Toast.LENGTH_LONG).show();
        Log.e("SOCK TIMEOUT", e.toString());
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        Log.e("OTHER EXCEPTIONS", e.toString());
    }

1 个答案:

答案 0 :(得分:2)

得到了解决。缺少在函数末尾抛出异常{。 duhhh

感谢@Alin提供了良好的提示。