【问题标题】:How can I identify the content-type after opening an HTTP connection?打开 HTTP 连接后如何识别内容类型?
【发布时间】:2014-02-13 18:42:09
【问题描述】:

我正在打开一个到我在程序中生成的 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;
    }
}

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

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

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

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

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

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

【问题讨论】:

    标签: java httpurlconnection httpcontent


    【解决方案1】:

    你可以使用getContentType:

    公共字符串getContentType() 在 API 级别 1 中添加

    返回由响应头字段 content-type 指定的内容的 MIME 类型,如果类型未知,则返回 null。

    【讨论】:

    • 问题:ico 资源我会得到什么字符串?
    • 注册的mime类型是image/vnd.microsoft.iconhere
    • 我得到null 的内容类型为cdn0.sbnation.com/uploads/hub/favicon/247/favicon-0666b2d5.ico,尽管当我通过 Firefox 连接到此 URL 时,我清楚地看到了一个“ico”。你知道如何解释这个吗?谢谢
    • 服务器没有在此 URL 的响应中设置 content-type 标头。
    • 那么这本质上是不是在大多数服务器中不太可能发生的服务器“错误”?
    猜你喜欢
    • 2017-04-15
    • 2019-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 2017-09-05
    相关资源
    最近更新 更多