Android的HTTP通信 XML解析和异步消息处理
2010-02-03 19:10:00 来源:WEB开发网while (readCount < fileSize && readNum != -1) {
readNum = inputStream.read(buffer);
if (readNum > -1) {
outputStream.write(buffer);
readCount = readCount + readNum;
int percent = (int) (readCount * 100 / fileSize);
if (percent > prevPercent) {
// 发送下载进度信息
sendMessage(FILE_DOWNLOAD_UPDATE, percent,
readCount);
prevPercent = percent;
}
}
}
outputStream.close();
sendMessage(FILE_DOWNLOAD_COMPLETE, savePath);
} catch (Exception e) {
sendMessage(FILE_DOWNLOAD_ERROR, e);
Log.e("MyError", e.toString());
}
}
}).start();
}
// 读取指定 url 地址的响应内容
public void download(final String url) {
new Thread(new Runnable() {
public void run() {
try {
sendMessage(FILE_DOWNLOAD_CONNECT);
URL sourceUrl = new URL(url);
URLConnection conn = sourceUrl.openConnection();
conn.setConnectTimeout(3000);
BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream(),
HTTP.UTF_8));
String line = null;
StringBuffer content = new StringBuffer();
while ((line = reader.readLine()) != null) {
content.append(line);
}
reader.close();
sendMessage(FILE_DOWNLOAD_COMPLETE, content.toString());
} catch (Exception e) {
sendMessage(FILE_DOWNLOAD_ERROR, e);
Log.e("MyError", e.toString());
}
}
}).start();
}
// 向 Handler 发送消息
private void sendMessage(int what, Object obj) {
// 构造需要向 Handler 发送的消息
Message msg = mHandler.obtainMessage(what, obj);
更多精彩
赞助商链接