2015-04-17 57 views
0

我需要驗證其模式URL(在schemaLocation屬性處引用)返回指向正確URL的HTTP 301錯誤的XML文件。而且,這些架構具有架構導入,其URL返回HTTP 301也指出正確的URL。如何使用返回HTTP 301的模式URL驗證XML?

JDom2似乎無法像簡單瀏覽器那樣解決HTTP 301錯誤。有沒有辦法強制JDom2正確解決這樣的錯誤?我必須重寫什麼JDom2類/方法來做到這一點?有沒有另一個Java XML庫可以做到這一點?

FYI:錯誤的URL是像http://schema-url和HTTP 301錯誤返回像

網址-----------------------一些後進展------------------------------

解決此問題的第一種方法可能是這樣的:

JDOM2 - Follow Redirects (HTTP Error 301)

即,使用folling片段:

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'. 

回答

0

的問題是,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()); 

    } 

}