【问题标题】:Detecting mime type in Java, wrong results在 Java 中检测 mime 类型,结果错误
【发布时间】:2015-09-17 16:04:01
【问题描述】:

我是 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 php mime-types


    【解决方案1】:

    该站点似乎拒绝默认 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();
    

    这将从上述网址返回image/jpeg

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

    【讨论】:

      猜你喜欢
      • 2015-10-05
      • 2016-05-20
      • 2012-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-13
      • 2018-04-08
      • 2013-04-17
      相关资源
      最近更新 更多