2016-09-14 58 views
-1

我以html格式接收來自外部服務的響應並將其直接傳遞給我的前端。但是,有時外部系統會返回損壞的html,這可能會導致我的網站上發生破損的頁面。因此,我想驗證這個html響應是否被破壞或有效。如果它是有效的,我會進一步傳遞它,否則在日誌中會被忽略。對後端的HTML驗證

通過什麼方式可以在Java中對後端進行驗證

謝謝。

+0

真正的問題是,爲什麼你的後端請求返回死/斷鏈接? – Fallenreaper

+0

http://stackoverflow.com/questions/4217801/a-html-validator-in-java檢查這個問題! –

回答

0

我找到了解決的HTML:

private static boolean isValidHtml(String htmlToValidate) throws ParserConfigurationException, 
     SAXException, IOException { 
    String docType = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" " + 
      "\"https://www.w3.org/TR/xhtml11/DTD/xhtml11-flat.dtd\"> " + 
      "<html xmlns=\"http://www.w3.org/1999/xhtml\" " + "xml:lang=\"en\">\n"; 

    try { 
     InputSource inputSource = new InputSource(new StringReader(docType + htmlToValidate)); 

     DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); 
     domFactory.setValidating(true); 
     DocumentBuilder builder = domFactory.newDocumentBuilder(); 
     builder.setErrorHandler(new ErrorHandler() { 
      @Override 
      public void error(SAXParseException exception) throws SAXException { 
       throw new SAXException(exception); 
      } 

      @Override 
      public void fatalError(SAXParseException exception) throws SAXException { 
       throw new SAXException(exception); 
      } 

      @Override 
      public void warning(SAXParseException exception) throws SAXException { 
       throw new SAXException(exception); 
      } 
     }); 

     builder.parse(inputSource); 
    } catch (SAXException ex) { 
     //log.error(ex.getMessage(), ex); // validation message 
     return false; 
    } 

    return true; 
} 

這種方法可以採用這種方式:

String htmlToValidate = "<head><title></title></head><body></body></html>"; 

    boolean isValidHtml = isValidHtml(htmlToValidate);