移动连接上的HttpRequest失败但没有抛出错误?

时间:2015-05-19 12:34:40

标签: android error-handling timeout apache-commons-httpclient

在我正在编写的Android应用程序中,我使用Php访问MySql数据库。 我使用AsyncTask和HttpClient。通过Wifi使用时,代码工作正常。 但是当使用2G / 3G时它会随机失败。

起初我没有设置ConnectionTimeOut或SOTimeOut然后它会无限期地继续下去。设置超时后,它会在超时后关闭。

在此期间没有例外。 这是我的asynctask

的doInBackground部分
class MyAsyncTask extends AsyncTask<String,Void,String>
{
    ProgressDialog pd;

    public MyAsyncTask(Context context) 
    {
        pd=new ProgressDialog(context);
        pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    }

    @Override
    protected void onPreExecute() 
    {
        pd.show();
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params) 
    {
        String url="<php url>";
        String line = "";
        StringBuffer sb=new StringBuffer();
        try 
        {
            final HttpParams hp = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(hp, 15000);
            HttpConnectionParams.setSoTimeout(hp, 15000);

            HttpClient client = new DefaultHttpClient(hp);
            HttpGet formData = new HttpGet(url);
            HttpResponse response = client.execute(formData);

            HttpEntity entity=response.getEntity();
            InputStream is=entity.getContent();
            InputStreamReader isr=new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);

            while((line=br.readLine())!=null)
            {
                sb.append(line);
            }
        }
        catch (ClientProtocolException e) 
        {
            Log.i("Tag","1. "+e.toString());
            return e.toString();
        }
        catch (IllegalStateException e) 
        {
            Log.i("Tag","2. "+e.toString());
            return e.toString();
        }
        catch (ConnectTimeoutException e)
        {
            Log.i("Tag","3. "+e.toString());
            return e.toString();
        }
        catch (SocketTimeoutException e)
        {
            Log.i("Tag","4. "+e.toString());
            return e.toString();
        }
        catch (IOException e) 
        {
            Log.i("Tag","5. "+e.toString());
            return e.toString();
        }
        catch (Exception e)
        {
            Log.i("Tag","6. "+e.toString());
            return e.toString();
        }
        return sb.toString();
    }

    @Override
    protected void onPostExecute(String result) 
    {
        Log.i("Tag","Result : "+result );
        pd.dismiss();
        //tv - textview 
        tv.setText(result);
        super.onPostExecute(result);
    }
}

没有执行任何catch语句.PostExecute只会记录一个空字符串。我希望有人能够解决这个问题,或者至少是解决这个问题的最佳方法。

我已经更新以显示我的完整asynctask类。没有太大的区别,你可以看到。但我注意到一些新的,当这种情况发生时,我很快在浏览器中输入了网址(Chrome),同样的情况发生了,有没有输出。 但是显示错误消息有504错误,如果我通过拉下来刷新屏幕,我得到了输出。但如果我重新输入网址,我也会遇到同样的错误。

0 个答案:

没有答案