检测 Java 中的 MIME 类型,结果错误

Detecting mime type in Java, wrong results

我是 Java 的新手,也许我遗漏了什么,但我试图获取 url http://www.bunspace.com/static/photobucket/15155/dancing_buns.jpg 的内容类型。

我尝试了两种方式:

1:

URL url = new URL(path);
URLConnection urlConnection = url.openConnection();
return urlConnection.getContentType();

2:

URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection)  url.openConnection();
connection.setRequestMethod("HEAD");
connection.connect();
return connection.getContentType();

两种方式都给了我结果"text/html; charset=ISO-8859-1"

显然 url 的类型是 image/jpeg,我也检查了 PHP:

$type = get_headers("http://www.bunspace.com/static/photobucket/15155/dancing_buns.jpg", 1);
print($type['Content-Type']);

PHP 返回 "image/jpeg"。

有没有办法以更可靠的方式在 Java 中输入 mime 类型?

该站点似乎拒绝默认的 Java 用户代理,即 "Java/1.7"(或您使用的任何版本)。有些网站这样做是为了避免琐碎的机器人。

因此您需要设置用户代理字符串 - 因此要扩展您的第二种方法:

URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection)  url.openConnection();
connection.setRequestProperty("User-Agent", "Not a Java Bot");
connection.setRequestMethod("HEAD");
connection.connect();
return connection.getContentType();

这将 return image/jpeg 从上述 URL.

当然,如果您不希望您的访问被注意到,您可以使用真实浏览器的用户代理字符串。