java - 为什么我的 PDF 文件的内容类型以 HTML 形式返回?

标签 java url web-crawler mime-types content-type

我尝试使用以下代码查看 Web URL 的内容类型。

有趣的是,给定 URL (http://www.jbssinc.com/inv_pr_pdf/2007-05-08.pdf") 的内容类型返回为 text/html ; charset=iso-8859-1 即使它是 PDF 文档。我想了解为什么。

这是我的代码:

public static void main(String[] args) throws MalformedURLException{
    URLConnection urlConnection = null;
    URL url  = new URL("http://www.jbssinc.com/inv_pr_pdf/2007-05-08.pdf");
    try {
        urlConnection = url.openConnection();
        urlConnection.setConnectTimeout(10*1000);
        urlConnection.setReadTimeout(10*1000);
        urlConnection.connect();

    } catch (IOException e) {
        System.out.println("Error in establishing connection.\n");
    }
    String contentType = "";
    /* If we were able to get a connection ---> */
    if (urlConnection != null) {
        contentType = urlConnection.getContentType();
    }
    System.out.println(contentType);
}

最佳答案

当我用 Java 访问此页面时,如果我尝试实际加载该页面,则会收到 403 - Forbidden 错误。这些错误页面是 HTML 页面,而不是 pdf 文件,因此这就是您看到的内容类型的原因。

该网站可能正在检测您的浏览器或使用某种其他机制来阻止自动下载,这就是为什么它可以在 Chrome、Firefox 和 IE 中运行,但不能在 Java 中运行。

您的代码可以在不同的 URL 下正常工作,例如 https://partners.adobe.com/public/developer/en/xml/AdobeXMLFormsSamples.pdf

对于此网络服务器,如果您将User-Agent指定为典型的浏览器值,它将允许您正常建立连接。

尝试在 urlConnection.connect() 之前添加此行:

urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");

See this answer for more information about setting the User-Agent 。不过,在执行此操作之前,您应该确保您没有以某种方式违反网站的服务条款。

通常,检查网站是否明确禁止应用下载其内容的方法是使用 http://example.com/robots.txt 文件。在这种情况下,这将是 http://www.jbssinc.com/robots.txt 。在这种情况下,该文件不会禁止机器人(您的程序)下载该特定文件,因此我认为您可以欺骗您的用户代理。在这种情况下,Java 被阻止的事实更有可能是用户错误。

进一步阅读:Is using a faked user agent allowed?

关于java - 为什么我的 PDF 文件的内容类型以 HTML 形式返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32339227/

相关文章:

java - Set 的奇怪 JSON 映射问题 - 缺少元素

java - 执行 ant 创建 jar 时出现 zip 大小错误

facebook - Facebook 和新 Twitter URL 中的 shebang/hashbang (#!) 是做什么用的?

asp.net、url 重写模块和 web.config

算法:确定主页的类型?

php - 谷歌代理是假爬虫?例如 : google-proxy-66-249-81-131. google.com

Python字典: Key with two values possible?

java - 有没有一种简单的方法可以使 log4j 更小?

javascript - 将参数传递给函数 onclick jQuery

java - 对自定义对象的 vector 进行排序