Android开发文件下载有时候下载文件的时候需要获取文件的名称及扩展名,但是下载链接不包含文件的扩展名及文件名,需要其他的方案解决,下面就有两个解决的方案。
一、通过HttpURLConnection
的提供的方法
public static String guessContentTypeFromStream(InputStream in);
BufferedInputStream bis = null;
HttpURLConnection connection = null;
URL url = new URL(strUrl);
connection = (HttpURLConnection)url.openConnection();
connection.connect();
bis = new BufferedInputStream(connection.getInputStream());
System.out.println("filetype:"+HttpURLConnection.guessContentTypeFromStream(bis));
二、获取connection.getHeaderField("Content-Disposition");
HttpURLConnection connection = null;
connection = (HttpURLConnection) new URL(url)
connection .openConnection();
connection.setRequestMethod("GET");
connection.connect();
int code = 0;
code = connection.getResponseCode();
if (code == HttpURLConnection.HTTP_OK) {
String fileName = connection.getHeaderField("Content-Disposition");
// 通过Content-Disposition获取文件名
if (fileName == null || fileName.length() < 1) {
// 通过截取URL来获取文件名
URL downloadUrl = connection.getURL();
// 获得实际下载文件的URL
fileName = downloadUrl.getFile();
fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
} else {
fileName = URLDecoder.decode(fileName.substring(fileName.indexOf("filename=") + 9), "UTF-8");
// 存在文件名会被包含在""里面,所以要去掉,否则读取异常
fileName = fileName.replaceAll("\"", "");
}
}