我的代码如下从url下载xml内容,这需要更多时间在wifi网络下载,我的xml只有29.2kb。我正在使用AsyncTask。
InputStream getInputStreamForUrl(String url) {
BufferedHttpEntity bufferedEntity = null;
InputStream is = null;
try {
bufferedEntity = download(url);
if (bufferedEntity != null) {
is = bufferedEntity.getContent();
if (is != null) {
BufferedReader feedReader = new BufferedReader(new InputStreamReader(is, Utility.UTF_ENCODING),
16 * 1024);
Utility.cacheFeed(feedReader, url);
}
}
} catch (NetworkNotAccessable e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (bufferedEntity != null) {
bufferedEntity.consumeContent();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return (url != null) ? Utility.getInputStreamForCache(url) : null;
}
下载(url)方法我使用HttpGet请求如下:
public BufferedHttpEntity download(String url)
throws ClientProtocolException, IOException,
IllegalStateException, NetworkNotAccessable {
HttpGet get = new HttpGet(url);
HttpResponse response = mDefaultHttpClient.execute(get);
int status = response.getStatusLine().getStatusCode();
if (status != 200) {
throw new NetworkNotAccessable(url + "error code:" + status);
}
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
while (bufHttpEntity.isStreaming()) {
try {
bufHttpEntity.wait(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return bufHttpEntity;
}
请告诉我有没有最好的方法来压缩整个网址并下载它。
答案 0 :(得分:2)
如果您说实际下载发生在' download(url)'方法然后我恐怕我看不到这种情况,也从getInputStream方法调用下载方法,你输入的输入流不能看到任何原因......
另外你为什么要使用bufHttpEntity.wait(500);这是阻塞状态(可能导致重大延迟)
在下载方法中使用以下代码来检索xml:
URL url = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
byte buffer[] = new byte[4096];
int count;
String xmlData = "";
while( (count = in.read(buffer)) != -1){
xmlData += new String(buffer, 0, count);
} finally {
urlConnection.disconnect();
}
Log.d(TAG, " Data: " + xmlData );