【问题标题】:How to validate XML with schema URLs that return HTTP 301?如何使用返回 HTTP 301 的架构 URL 验证 XML?
【发布时间】:2015-06-24 03:41:02
【问题描述】:

我需要验证一个 XML 文件,其架构 URL(在 schemaLocation 属性中引用)返回一个 HTTP 301 错误,指出正确的 URL。此外,这些架构具有架构导入,其 URL 返回 HTTP 301 并指出正确的 URL。

JDom2 似乎无法像简单的浏览器那样解决 HTTP 301 错误。有没有办法强制 JDom2 正确解决此类错误?我必须重写什么 JDom2 类/方法才能做到这一点?是否有另一个 java XML 库可以做到这一点?

仅供参考:错误的 URL 类似于 http://schema-url,而 HTTP 301 错误返回的 URL 类似于

------------------------ 后来有一些进展 --------- ---------

解决这个问题的第一种方法可能是这样的:

JDOM2 - Follow Redirects (HTTP Error 301)

即,使用以下 sn-p:

URL httpurl = new URL(.....);
HTTPURLConnection conn = (HTTPUrlConnection)httpurl.openConnection();
conn.setInstanceFollowRedirects(true);
conn.connect();
Document doc = saxBuilder.build(conn.getInputStream());

但在我的例子中,应用程序从 gzip xml 文件中读取 xml,所以它不会工作。我决定使用类似的东西:

final SAXBuilder builder = new SAXBuilder(XMLReaders.XSDVALIDATING);
builder.setEntityResolver(new RedirectEntityResolver());
document = builder.build(isXml);

isXml 是解压后的 XML 文件输入流,RedirectEntityResolver 编码如下:

public class RedirectEntityResolver implements EntityResolver {

    public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {

        URL httpurl = new URL(systemId);
        HttpURLConnection conn = (HttpURLConnection) httpurl.openConnection();
        conn.setInstanceFollowRedirects(true);
        conn.connect();

        return new InputSource(conn.getInputStream());
    }

}

但它不起作用。 HttpURLConnection 似乎无法解决重定向,我得到同样的错误:

org.xml.sax.SAXParseException: s4s-elt-character: Non-whitespace characters are not allowed in schema elements other than 'xs:appinfo' and 'xs:documentation'. Saw 'Document Moved'.

【问题讨论】:

    标签: java xml url redirect xsd


    【解决方案1】:

    问题是conn.setInstanceFollowRedirects(true); 不工作。查看URLConnection Doesn't Follow Redirect anwsers

    相反,使用像下面这样的EntityResolver,它可以完美运行:

    public class RedirectEntityResolver implements EntityResolver {
    
    
        public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
    
            URL obj = new URL(systemId);
            HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
    
            int status = conn.getResponseCode();
            if ((status != HttpURLConnection.HTTP_OK) &&
                (status == HttpURLConnection.HTTP_MOVED_TEMP
                || status == HttpURLConnection.HTTP_MOVED_PERM
                || status == HttpURLConnection.HTTP_SEE_OTHER)) {
    
                String newUrl = conn.getHeaderField("Location");
                conn = (HttpURLConnection) new URL(newUrl).openConnection();
            }
    
            return new InputSource(conn.getInputStream());
    
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-07
      相关资源
      最近更新 更多