有的時候下載鏈接的后綴並不是文件真實名字,我們想要獲得其真實文件名需要進行一些處理:
主要是獲得header信息
代碼如下:
String href = "https://yyyyy.xxxxxxx(下載Url)"; URL url = null; try { url = new URL(href); } catch (MalformedURLException e) { e.printStackTrace(); } try { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect();//獲取文件名和擴展名 conn.getResponseCode(); href = conn.getURL().toString(); //獲取header 確定文件名和擴展名,並防止亂碼 fileName = new String(conn.getHeaderField("Content-Disposition").getBytes("ISO-8859-1"), "UTF-8"); System.out.println(fileName); } catch (IOException e) { e.printStackTrace(); }
添加getBytes方法 :new String(conn.getHeaderField("Content-Disposition").getBytes("ISO-8859-1"), "UTF-8")是為了防止亂碼
效果如圖:
