2

I'm developing some kind of android mail app and I get each mail attachments as an ArrayList of urls from a rest api and I want to use them in some kind of attachment section. I need to check the urls and pass image links to a preview adapter using glide api and show other urls (other file formats, like .pdf, .docx or ...) in another section as a download link.

Is there any way to know if the url is link to a image file or not before downloading it?


I know there are seemingly similar threads that are answered already but this is different in two ways. First I want to to know if the url is link to image or not before downloading it. Second I don't want to use static extension check. Because there are like tons of different extensions like .jpg, .png,... and they may change and I don't want to update my app with each change.

Parham
  • 116
  • 10

4 Answers4

2

There is a way you can do it but I'm not sure its the best approach.

Code:

new Thread(new Runnable() { // if already doing the checking on network thread then no need to add this thread
        @Override
        public void run() {
            try {
                URLConnection connection = new URL("image url here").openConnection();
                String contentType = connection.getHeaderField("Content-Type");
                boolean image = contentType.startsWith("image/"); //true if image 
                Log.i("IS IMAGE", "" + image);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();

Hope this helps!

Ahmad Sabeh
  • 526
  • 5
  • 18
  • 1
    Thanks! It worked. However I had to add a `runOnUiThread` inside it to change my ui adapter. – Parham Jul 30 '19 at 09:24
1

You can provide additional fields,which can help you identify file format, in your rest API.

马树忠
  • 21
  • 3
  • This is correct however I wanted to know if there is any way that I could do it without changing the rest api. So that Backend developer wouldn't have to change the already developed api. – Parham Jul 30 '19 at 08:30
1

You can checkout response content-type. Checkout this answer:

https://stackoverflow.com/a/5802223

Community
  • 1
  • 1
P.Rostami
  • 11
  • 1
  • Welcome to SO. This is more like a comment than an answer so when you are able to comment on posts you could do that. – Mike Poole Jul 30 '19 at 08:59
0

If you have the URI you could: use this for the full path and substring after the last "."

Coder123
  • 784
  • 2
  • 8
  • 29