我正在打开一个到我在程序中生成的 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
中,我想识别内容类型。例如:
连接到 http://www.google.com 时,内容类型为文本。
连接到 http://www.google.com/favicon.ico 时,内容类型为图像。
我无法使用 URL 结构来确定这一点。例如:
- 连接到 http://www.advertising.com/favicon.ico 时,响应代码为 200,但内容类型为 Text(内容本身为“未找到请求的文件 favicon.ico。”)。
我知道如何使用 InputStream
对象读取内容,但是:
如果可能的话,我希望避免获取内容本身。
我不明白它如何帮助我确定内容类型。
任何想法都将受到高度赞赏...谢谢。
最佳答案
您可以使用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/