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

检测Java中的mime类型,结果错误,java,php,mime-types,Java,Php,Mime Types,我是Java的新手,也许我遗漏了一些东西,但我尝试获取url的内容类型 我试过两种方法: 1: 2: 两种方法都给了我结果“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']);

我是Java的新手,也许我遗漏了一些东西,但我尝试获取url的内容类型

我试过两种方法:

1:

2:

两种方法都给了我结果“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();
这将从上述URL返回
image/jpeg

当然,如果您不想让别人注意到您的访问,您可以使用真实浏览器的用户代理字符串

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