HttpURLConnection从链接下载数据存放本地临时文件,Java
private File download(String url) throws Exception {
HttpURLConnection connection = getConnection(url);
int contentLength = connection.getContentLength();
String msg = connection.getResponseMessage();
System.out.println(msg);
InputStream is = connection.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
File tempFile = File.createTempFile(UUID.randomUUID().toString(), "");
FileOutputStream fos = new FileOutputStream(tempFile);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int c;
int count = 0;
byte[] buf = new byte[1024 * 4];
double pcent;
while (true) {
c = bis.read(buf);
if (c == -1)
break;
bos.write(buf, 0, c);
count = count + c;
pcent = (count / (double) contentLength) * 100;
System.out.print("已下载:" + String.format("%.2f", pcent) + "% \r");
}
bis.close();
bos.close();
fos.close();
return tempFile;
}
private HttpURLConnection getConnection(String u) throws Exception {
URL url = new URL(u);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Connection", "Keep-Alive");
connection.connect();
return connection;
}