HttpURLConnection下载了文件名

是否可以获取使用HttpURLConnection下载的文件的名称?

URL url = new URL("http://somesite/getFile?id=12345"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setAllowUserInteraction(false); conn.setDoInput(true); conn.setDoOutput(true); conn.connect(); InputStream is = conn.getInputStream(); 

在上面的示例中,我无法从URL中提取文件名,但服务器将以某种方式向我发送文件名。

您可以使用HttpURLConnection.getHeaderField(String name)来获取Content-Disposition标头,该标头通常用于设置文件名:

 String raw = conn.getHeaderField("Content-Disposition"); // raw = "attachment; filename=abc.jpg" if(raw != null && raw.indexOf("=") != -1) { String fileName = raw.split("=")[1]; //getting value after '=' } else { // fall back to random generated file name? } 

正如其他答案所指出的,服务器可能会返回无效的文件名,但您可以尝试一下。

坦率的回答是 – 除非Web服务器在Content-Disposition标头中返回文件名,否则没有真正的文件名。 也许你可以在/之后和查询字符串之前将它设置为URI的最后部分。

 Map m =conn.getHeaderFields(); if(m.get("Content-Disposition")!= null) { //do stuff } 

检查响应中的Content-Disposition :附件标头。

 Map map = connection.getHeaderFields (); if ( map.get ( "Content-Disposition" ) != null ) { String raw = map.get ( "Content-Disposition" ).toString (); // raw = "attachment; filename=abc.jpg" if ( raw != null && raw.indexOf ( "=" ) != -1 ) { fileName = raw.split ( "=" )[1]; // getting value after '=' fileName = fileName.replaceAll ( "\"", "" ).replaceAll ( "]", "" ); } }