简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM