Search code examples
javaandroidparsingurl-parsing

How to get filename and extension from web URL also from URL with additional parameters


I have tried

new File(new URI(url).getPath()).getName()

to get the name and

fileName.substring(i+1);

to get extension

but some urls are problematic and this method doesn't work if I have something like

https://wallpaperclicker.com/wallpaper/Download.aspx?wallfilename=samplehd-pics-87908344.jpg"

or

https://spxt-sjc2-1.cdnagram.com/t51.2885-15/s980x480/e35/20969138_31213_564630462529635_5170096177993632_n.jpg?ig_cache_key=M0003NTyMTc3MjY5MDE4Nw%3D%3D.2"

I need a solution that can handle correctly also URLS with additional parameters.


Solution

  • It is impossible to find out the correct extension from the URI. the webserver can fool you to download a .sh where the link might say it's .jpg (Symbolic links).

    comming to the question, you can make a connection and use getContentType etc to fetch the information that is set by the server if url parsing is not working.

        URL url = new URL(fileURL);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        int responseCode = httpConn.getResponseCode();
    
        // always check HTTP response code first
        if (responseCode == HttpURLConnection.HTTP_OK) {
            String fileName = "";
            String disposition = httpConn.getHeaderField("Content-Disposition");
            String contentType = httpConn.getContentType();
    
            if (disposition != null) {
                // extracts file name from header field
                int index = disposition.indexOf("filename=");
                if (index > 0) {
                    fileName = disposition.substring(index + 10,
                            disposition.length() - 1);
                }
            }
         }
    

    NOTE: Code is not tested. Hopefully, It gives you a hint.