下面是写的java工具类
import org.apache.commons.io.FilenameUtils;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DownloadUtil {
public Boolean DownloadAudio(String DownloadUrl) {
String newUrl="C:\\Users\\Administration\\Desktop";
URL url = null;
HttpURLConnection con = null;
InputStream in = null;
FileOutputStream out = null;
String fileUrl=null;
try {
url = new URL(DownloadUrl);
//建立http连接,得到连接对象
con = (HttpURLConnection) url.openConnection();
//输入流读取文件
in = con.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int len = 0;
while ((len = in.read(b)) != -1) {
bos.write(b, 0, len);
}
if (null != bos) {
bos.close();
}
//转化为byte数组
byte[] data = bos.toByteArray();
//建立存储的目录、保存的文件名
File file = new File(newUrl);
if (!file.exists()) {
file.mkdirs();
}
//修改文件名 用时间重命名
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
Date date = new Date(System.currentTimeMillis());
String s = url.toString();
//获取文件类型
FilenameUtils filenameUtils = new FilenameUtils();
String extension = filenameUtils.getExtension(s);
if (extension.indexOf("?") != -1) {
extension = extension.substring(extension.lastIndexOf(".") + 1, extension.lastIndexOf("?"));
}
//String fileType=s.substring(s.lastIndexOf("."),s.length());
File res = new File(file + File.separator + formatter.format(date) + "." + extension);
fileUrl=res.getAbsolutePath();
//写入输出流
out = new FileOutputStream(res);
out.write(data);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭流
try {
if (null != out)
out.close();
if (null != in)
in.close();
} catch (IOException e) {
e.printStackTrace();
}
boolean exists=false;
try {
exists =new File(fileUrl).exists();
} catch (Exception e) {
e.printStackTrace();
}
return exists;
}
}
}
因为 HttpURLConnection 对象只会处理一次 301 重定向,但是这个链接发生了两次重定向,所以 HttpURLConnection 下载得到的只是第一次重定向的结果
真实的地址在第二次重定向里
所以这里你需要单独处理一次 301
URL url = new URL("http://www.telerik.com/docs/default-source/fiddler/addons/fiddlercertmaker.exe?sfvrsn=2");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("User-Agent", "5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36");
con.connect();
String url1 = con.getHeaderField("Location"); // 这个才是真实的下载地址
downloadUsingStream(url1,"D:/12346.exe");
有用望采纳