显示Web服务URL连接超时Android的警报消息

时间:2013-08-29 06:11:27

标签: java android web-services android-layout android-intent

我正在调用webservice网址并在Andriod中成功获得响应

这里是我的代码:

protected String doInBackground(String... params) {
    HttpResponse response = null;
    // TODO Auto-generated method stub
    // String url=params[0];
    try {

    final HttpParams httpParams = new BasicHttpParams();
    HttpClient httpclient = new DefaultHttpClient(httpParams);

    HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 10000);
    int timeoutSocket = 60*1000;
    HttpConnectionParams.setSoTimeout(httpParams, timeoutSocket);

    HttpGet request = new HttpGet("WebServiceURL");
        response = httpclient.execute(request);

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Log.d("Exaception1>>>","Exaception1>>");        


    } catch (IOException e) {
        // TODO Auto-generated catch block
        Log.d("Exaception2>>>","Exaception1>>");

        e.printStackTrace();
    }
    statusLine = response.getStatusLine();
    if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            response.getEntity().writeTo(out);
            out.close();
            responseString = out.toString();
            // Whatever you wanna do with the response
            // Log.d("response", responseString);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            Log.d("Exaception3>>>","Exaception1>>");

            e.printStackTrace();

        }

    } else {
        // Close the connection.
        try {
            response.getEntity().getContent().close();
            throw new IOException(statusLine.getReasonPhrase());

        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    return responseString;
}

但有时候WebService URL不会处于活动状态,我的要求是向用户显示连接TimeOut的警告消息,可以帮助吗?

3 个答案:

答案 0 :(得分:1)

您可以在doInBackground中捕获ConnectTimeoutException(),以便在异步任务的onPostExecute()中显示警报

答案 1 :(得分:1)

创建一个具有成功,错误和超时等方法的接口。 将ConnectTimeoutException捕获到异步任务并调用接口的超时方法。 在asyncTask postexecute()或执行异步任务的位置处理此超时方法。

答案 2 :(得分:0)

抓住ConnectTimeOutException中的doInBackground并处理错误

catch (ConnectTimeoutException e) {
            // handle exception
        }