0

我正在调用 Web 服务 url 并在 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 不会处于活动状态,我的要求是向用户显示连接超时的警报消息,有人可以帮忙吗?

4

3 回答 3

1

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

于 2013-08-29T06:18:17.730 回答
1

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

于 2013-08-29T06:35:25.590 回答
0

抓住ConnectTimeOutException你的doInBackground并处理他们的错误

catch (ConnectTimeoutException e) {
            // handle exception
        }
于 2013-08-29T06:38:27.413 回答