Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpURLConnection downloaded file name

Is it possible to get the name of a file downloaded with 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();

In the example above I cannot extract the file name from the URL, but the server will send me the file name in some way.

like image 683
capitano666 Avatar asked Jun 12 '12 11:06

capitano666


People also ask

How do I read HttpURLConnection response?

Set the request method in HttpURLConnection instance, default value is GET. Call setRequestProperty() method on HttpURLConnection instance to set request header values, such as “User-Agent” and “Accept-Language” etc. We can call getResponseCode() to get the response HTTP code.

What is the difference between URLConnection and HttpURLConnection?

URLConnection is the base class. HttpURLConnection is a derived class which you can use when you need the extra API and you are dealing with HTTP or HTTPS only. HttpsURLConnection is a 'more derived' class which you can use when you need the 'more extra' API and you are dealing with HTTPS only.

Do I need to disconnect HttpURLConnection?

Yes you need to close the inputstream first and close httpconnection next. As per javadoc. Each HttpURLConnection instance is used to make a single request but the underlying network connection to the HTTP server may be transparently shared by other instances.


1 Answers

You could use HttpURLConnection.getHeaderField(String name) to get the Content-Disposition header, which is normally used to set the file name:

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?
}

As other answer pointed out, the server might return invalid file name, but you could try it.

like image 162
Pau Kiat Wee Avatar answered Oct 12 '22 11:10

Pau Kiat Wee