简体   繁体   English

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

[英]Detecting mime type in Java, wrong results

I'm sort of newbie in Java, maybe i'm missing something, but i tried to get the content type of the url http://www.bunspace.com/static/photobucket/15155/dancing_buns.jpg . 我是Java的新手,也许我错过了什么,但我试图得到网址的内容类型http://www.bunspace.com/static/photobucket/15155/dancing_buns.jpg

I tried in 2 ways: 我试过两种方式:

1: 1:

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

2: 2:

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

both ways gave me result "text/html; charset=ISO-8859-1" 两种方式都给了我“text / html; charset = ISO-8859-1”的结果

Obviously the type of the url is image/jpeg, and i also checked with PHP: 显然,url的类型是image / jpeg,我也用PHP检查过:

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

PHP returned "image/jpeg". PHP返回“image / jpeg”。

Is there a way to get mime type in Java in more trustful way? 有没有办法以更可靠的方式在Java中获取mime类型?

That site seems to reject the default Java user agent, which is "Java/1.7" (or whatever version you use). 该站点似乎拒绝默认的Java用户代理,即“Java / 1.7”(或您使用的任何版本)。 Some sites do that to avoid trivial bots. 一些网站这样做是为了避免琐碎的机器人。

So you need to set the user agent string - so to extend your second method: 所以你需要设置用户代理字符串 - 所以要扩展你的第二个方法:

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();

This will return image/jpeg from the aforesaid URL. 这将从上述URL返回image/jpeg

Of course, you can use the user agent string of a real browser if you don't want your access to be noticed. 当然,如果您不希望您的访问被注意,您可以使用真实浏览器的用户代理字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM