java - 打开 HTTP 连接后如何识别 content-type?

标签 java httpurlconnection httpcontent

我正在打开一个到我在程序中生成的 URL 的 HTTP 连接:

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

现在,在情况 2 中,我想识别内容类型。例如:

我无法使用 URL 结构来确定这一点。例如:

我知道如何使用 InputStream 对象读取内容,但是:

  1. 如果可能的话,我希望避免获取内容本身。

  2. 我不明白它如何帮助我确定内容类型。

任何想法都将受到高度赞赏...谢谢。

最佳答案

您可以使用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.

关于java - 打开 HTTP 连接后如何识别 content-type?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21304416/

相关文章:

java - 无法找到显式 Activity 类并且无法实例化 Activity

java - 如何在 Java 中声明数组元素 volatile?

java - 没有看到使用 Autowired 注释的 bean,没有任何帮助

android - 调用api时只得到一半的json日期

C# 无法将欧元符号打印到文件中(使用 Excel 打开时)

java - 使用 Guice 将 play.Environment 注入(inject) Jackson 序列化器

java - 如何计算服务器发送给我的 100 个继续的数量?

java - HttpURLConnection 超时默认值

c# - HttpContent.ReadAsAsync 在哪里?

c# - HttpContent.ReadAsStringAsync 导致请求挂起(或其他奇怪的行为)