在 Java/Jboss 中读取来自 post 的响应时如何避免 dtd 验证

How do i avoid dtd validation when reading response from a post in Java/Jboss

我 运行 在 windows 7 上 JBoss 8.1,并尝试 post 请求以获得 xml 响应并将其映射到我的POJO的。我已经用 1 url 这样

完成了
WebTarget webTarget = ClientBuilder.newClient().target(queryString);
Bean bean=webTarget.request(MediaType.APPLICATION_XML).get(Bean.class);

这正是我想要的 - 一堆 类 对应于 xml 结构。

现在我想对 post 和另一个 url 做同样的事情,但我最终得到了 FileNotFoundException 和对 xml 中 dtd 文件的引用:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE oxip SYSTEM "combinations.dtd">

我不想进行验证,所以我做了以下操作:

javax.ws.rs.core.Response vResponse;
WebTarget target=ClientBuilder.newClient().target(queryString);
response = target.request(MediaType.TEXT_XML).post(Entity.text(apiRequest));
String string = vResponse.readEntity(String.class);


JAXBContext jaxbContext = JAXBContext.newInstance(Bean.class);
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
saxParserFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
XMLReader xmlReader = saxParserFactory.newSAXParser().getXMLReader();
InputSource inputSource = new InputSource(new StringReader(string));
SAXSource source = new SAXSource(xmlReader, inputSource);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Bean bean = (Bean) unmarshaller.unmarshal(vSource);

有没有办法避免显式使用 SaxParser 和 JaxBContext,比如将 jboss jaxb 配置为不使用验证??

通过插入以下代码,问题已解决:

XMLReader vXmlReader = vSAXParserFactory.newSAXParser().getXMLReader();

//To avoid validating against external dtd which does not exist
EntityResolver entityResolver = new EntityResolver()  {
@Override
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
    return new InputSource(new StringReader(""));
  }
};

vXmlReader.setEntityResolver(entityResolver);

InputSource vInputSource = new InputSource(new StringReader(vMostPlayedResponse));