为什么我得到的 PDF 文件的内容类型返回为 HTML?

Why am I getting content type of a PDF file is returned as HTML?

我正在尝试使用以下代码查看 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?