How can I identify the content-type after opening an HTTP connection?

1.4k views Asked by At

I am opening an HTTP connection to a URL that I am generating within my program:

String url = INPUT_URL;
HttpURLConnection connection;
while (true)
{
    connection = (HttpURLConnection)new URL(url).openConnection();
    connection.setInstanceFollowRedirects(true);
    switch (connection.getResponseCode()/100)
    {
    case 3:
        url = connection.getHeaderField("Location");
        break;
    case 4:
    case 5:
        // Report some error
        return;
    }
}

Now, in case 2 I want to identify the content-type. For example:

I cannot use the URL structure in order to determine that. For example:

I know how to read the content using an InputStream object, but:

  1. I wish to avoid fetching the content itself if possible.

  2. I don't see how it can help me determine the content-type.

Any ideas would be highly appreciated... thanks.

1

There are 1 answers

6
Henry On BEST ANSWER

You could use getContentType:

public String getContentType () Added in API level 1

Returns the MIME-type of the content specified by the response header field content-type or null if type is unknown.