Anggrayudi H
Anggrayudi H

Reputation: 15165

Checking content type from URL

I asked this question before and Evgeniy Dorofeev answered it. Although worked for direct link only, but I accepted his answer. He just told me about check the content type from direct link:

String requestUrl = "https://dl-ssl.google.com/android/repository/android-14_r04.zip";
URL url = new URL(requestUrl);
URLConnection c = url.openConnection();
String contentType = c.getContentType();

As far I know, there are two URL types to download a file:

I need to check whether it is a file or webpage. I must download it if the content type is a file.

So my question:

Thanks for your help.

Upvotes: 4

Views: 18096

Answers (4)

Astrit Veliu
Astrit Veliu

Reputation: 1582

This one worked for me, you have to use retrofit to check the headers of response. First you have to define an endpoint to call it with the url you want to check:

@GET
suspend fun getContentType(@Url url: String): Response<Unit>

Then you call it like this to get the content type header:

api.getContentType(url).headers()["content-type"]

Upvotes: 0

Karan Datwani
Karan Datwani

Reputation: 795

MimeTypeMap.getFileExtensionFromUrl(url)

Upvotes: 0

omerfarukdogan
omerfarukdogan

Reputation: 869

After you open an URLConnection, a header file is returned. There are some information about the file in it. You can pull what you want from there. For example:

URLConnection u = url.openConnection();
long length = Long.parseLong(u.getHeaderField("Content-Length"));
String type = u.getHeaderField("Content-Type");

length is size of the file in bytes, type is something like application/x-dosexec or application/x-rar.

Upvotes: 10

Malt
Malt

Reputation: 30335

Such links redirect browsers to the actual content using HTTP redirects. To get the correct content type, all you have to do is tell HttpURLConnection to follow the redirects by setting setFollowRedirects() to true (documented here).

Upvotes: 1

Related Questions