我使用下面的代码从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秒。 我希望在请求和响应之间显示此时的图像。
最好的方法是什么?
任何帮助都将不胜感激。
答案 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) {
}