我是 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 返回“图像/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();
这将从上述 URL 返回 image/jpeg
。
当然,如果您不希望您的访问被注意到,您可以使用真实浏览器的用户代理字符串。
关于java - 在 Java 中检测 mime 类型,结果错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31145379/