public class DownloadTest {
public static void main(String[] args) {
try {
HttpURLConnection connection = (HttpURLConnection) new URL("http://skycnxz2.wy119.com/4/wandoujia.apk.apk").openConnection();
connection.setRequestMethod("GET");
int code = connection.getResponseCode();
if (code == 200) {
// Map<String, List<String>> fields = connection.getHeaderFields();
// for (Map.Entry<String, List<String>> entry : fields.entrySet()) {
// System.out.println(entry.getKey());
// System.out.println(entry.getValue());
// System.out.println("===================");
// }
int contentLength = connection.getContentLength();
InputStream is = connection.getInputStream();
FileOutputStream fos = new FileOutputStream("test.apk");
long sum = 0;
byte[] buffer = new byte[102400];
int length;
long startTime = System.currentTimeMillis();
while ((length = is.read(buffer)) != -1) {
fos.write(buffer, 0, length);
sum += length;
float parent = sum * 100.0f / contentLength;
System.out.print("\r[");
int p = (int) parent / 2;
for (int i = 0; i < 50; i++) {//进度条实现
if (i < p) {
System.out.print('=');
} else if (i == p){
System.out.print('>');
} else {
System.out.print(' ');
}
}
System.out.print(']');
System.out.printf("\t%.2f%%", parent);
long speed = sum * 1000 / (System.currentTimeMillis() - startTime);
if (speed > (1 << 20)) {
System.out.printf("\t%d MB/s", speed >> 20);
} else if (speed > (1 << 10)) {
System.out.printf("\t%d KB/s", speed >> 10);
} else {
System.out.printf("\t%d B/s", speed);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
HttpURLConnection实现文件下载
最新推荐文章于 2024-01-04 13:29:52 发布