javacontent-typeforce-download

getContentType method returning always 'application/force-download'


I have an URL to file which I can download. It looks like this:

 http://<server>/recruitment-mantis/plugin.php?page=BugSynchronizer/getfile&fileID=139&filehash=3e7a52a242f90c23539a17f6db094d86

How to get content type of this file? I have to admin that in this case simple:

   URL url = new URL(stringUrl);

   URLConnection urlConnection = url.openConnection();
   urlConnection.connect();

   String urlContent = urlConnection.getContentType();

returning me application/force-download content type in every file (no matter is jpg or pdf file). I want to do this cause I want to set extension of downloaded file (which can be various). How to 'get around' of this application/force-download content type? Thanks in advance for your help.


Solution

  • Check urlConnection.getHeaderField("Content-Disposition") for a filename. Usually that header is used for attachments in multipart content, but it doesn't hurt to check.

    If that header is not present, you can save the URL to a temporary file, and use probeContentType to get a meaningful MIME type:

    Path tempFile = Files.createTempFile(null, null);
    try (InputStream urlStream = urlConnection.getInputStream()) {
        Files.copy(urlStream, tempFile, StandardCopyOption.REPLACE_EXISTING);
    }
    String mimeType = Files.probeContentType(tempFile);
    

    Be aware that probeContentType may return null if it can't determine the type of the file.