在Android中显示httpGet和响应之间的进度图像

时间:2016-01-16 12:19:08

标签: java android httprequest httpresponse http-get

我使用下面的代码从Web服务获取XML文件:

public String getXmlFromUrl(String url) {
         String xml = null;

        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet HttpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(HttpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            xml = EntityUtils.toString(httpEntity,"UTF-8");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // return XML
        return xml;
    }

Web服务响应请求大约需要3-4秒。 我希望在请求和响应之间显示此时的图像。

最好的方法是什么?

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:2)

使用AsyncTask

private class LongOperation extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute() {

         // Show image Here
        }
        @Override
        protected String doInBackground(String... params) {
             String xml = null;

        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet HttpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(HttpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            xml = EntityUtils.toString(httpEntity,"UTF-8");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
            return null;
        }





        @Override
        protected void onPostExecute(String result) {
        /Handle Result From server
        }


        @Override
        protected void onProgressUpdate(Void... values) {
        }