Android HttpPost超时异常不起作用

时间:2012-07-10 18:07:38

标签: android android-asynctask http-post

我正在尝试将我的应用设置为在HttpPost上3秒后抛出超时异常。我正在从ASyncTask执行此请求。出于某种原因,即使我给它一个不存在的域,它会挂起大约一两分钟,然后抛出最后一个异常。为什么我的Timeout Exceptions无法正常工作?

protected Void doInBackground(String... params) {
            HttpPost httpPost = new HttpPost("http://hgfdhgfdhgfdhfgdhgfdhgfdhfgd.com");
            HttpParams httpParameters = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParameters, 3000);
            HttpConnectionParams.setSoTimeout(httpParameters, 3000);
            DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
            try {
                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is =  httpEntity.getContent();  

            } catch(ConnectTimeoutException e){
                Log.e("Timeout Exception: ", e.toString());
            } catch(SocketTimeoutException ste){    
                Log.e("Timeout Exception: ", ste.toString());
            } catch (Exception e) {
                Log.e("log_tag", "Error in http connection "+e.toString());
            }

            try {
                BufferedReader br = new BufferedReader(new InputStreamReader(is));
                StringBuilder sb = new StringBuilder();
                String line = "";
                while((line=br.readLine())!=null){
                    sb.append(line+"\n");
                }
                is.close();
                result=sb.toString();
            } catch (Exception e) {
                Log.e("log_tag", "Error converting result "+e.toString());
            }
            return null;

        }

1 个答案:

答案 0 :(得分:1)

不要在那里打电话。

当出现带有特定错误消息的异常时,为什么不返回null。

在postexecute方法中,做结果为null时需要做的事情。