0

I'm trying to download a file using the below code. I need to determine the filename and mime type of the file being download. The URL that I'm downloading from does not contain the filename. I've looked at the methods pertaining to the buffered streams used below and don't see any methods to do that.

    con = (HttpURLConnection) url.openConnection();

    //authenticate this request
    if (passwordAuthentication != null) {
        String auth = passwordAuthentication.getUserName()+":"+passwordAuthentication.getPassword();
        con.setRequestProperty("Authentication", Base64.encodeBase64(auth.getBytes()).toString());
    }

    BufferedInputStream bis = new BufferedInputStream(con.getInputStream());
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file.getName()));
    while ((i = bis.read()) != -1) {
        bos.write(i);
    }
    bos.flush();
    bis.close();

I see that I can get it via String contentType = con.getHeaderField("Content-Type");, but that returns text/html not the ContentType of the actual file being downloaded.

Edit: This is NOT a duplicate question, the other method does not provide a solution, described below.

I've now tried saving the file without a file extension and using MagicMatch match = Magic.getMagicMatch(file, true); but it returns text/plain. I'm guessing that's because I saved it without a file extension.

Ben
  • 60,438
  • 111
  • 314
  • 488
  • @Perception The only difference here is that I have an authentication layer I need to get past before I can determine the mime type. – Ben Mar 06 '13 at 05:09
  • you might want to give the JMimeMagic library a whirl. It can probe content types from underlying byte streams (aka, even if file extension, content type is missing). I can't vouch for its detection rate, but its higher than URLConnections probe method, thats for sure. – Perception Mar 06 '13 at 06:47

1 Answers1

2

In Java 7, you can now use Files.probeContentType(path)

Jeff
  • 98
  • 4
  • Well, the trick here is that the file I'm downloading is located at a URL. It's also an authenticated request. So it requires a username/password in order to access the file at the destination URL. I also have to have a filename in order to download the file. Which means I have to have already defined a file extension :-\ – Ben Mar 06 '13 at 04:52
  • You can also try [URLConnection.guessContentTypeFromStream(InputStream)](http://docs.oracle.com/javase/6/docs/api/java/net/URLConnection.html#guessContentTypeFromStream%28java.io.InputStream%29). This method directly inspects the content of the input stream. – Jeff Mar 06 '13 at 05:12