java - 如何通过 https URL 针对 XSD 验证 XML 文件?

标签 java xml validation https xsd

我想使用位于安全 https 站点的架构来验证 XML 文件。如何告诉 validator 排除自签名证书或使用 https URL?我有一个名为 test.xml 的文件和一个位于 https://localhost:1234/module/testschema.xsd 的架构。 。我正在使用相同的代码here 。如果我使用常规 URL ( http://localhost/module/testschema.xsd ),效果很好。如果我用 https URL 替换,则会收到此错误:

schema_reference.4:无法读取架构文档“https://localhost:1234/module/testschema.xsd” ',因为1)找不到该文档; 2)文档无法读取; 3)文档的根元素不是<xsd:schema> .

复制代码:

public boolean validateFile(String xml, String strSchemaLocation)
{
Source xmlFile = null;
try {
    URL schemaFile = new URL(strSchemaLocation);
    xmlFile = new StreamSource(new File(xml));
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = schemaFactory.newSchema(schemaFile);
    Validator validator = schema.newValidator();
    validator.validate(xmlFile);
    System.out.println(xmlFile.getSystemId() + " is valid");
} catch (SAXException e) {
    System.out.println(xmlFile.getSystemId() + " is NOT valid");
    System.out.println("Reason: " + e.getLocalizedMessage());
    return false;
} catch (IOException ioe) {
    System.out.println("IOException");
    return false;
}

return true;
}

最佳答案

这与模式验证关系不大。您的问题是您需要建立 HTTPS 连接并信任自签名证书。请参阅How can I use different certificates on specific connections?或者用谷歌搜索一下。

我认为您无法使用采用 File 的 SchemaFactory.newSchema 工厂方法,因此只需使用采用 StreamSource 的工厂方法即可:

URL schemaFile = new URL(strSchemaLocation);
HttpsURLConnection schemaConn = (HttpsURLConnection)schemaFile.openConnection();
// Magic from the other answer to accept self-signed cert
InputStream is = schemaConn.getInputStream();
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(new StreamSource(is));

(我省略了 try..catch 来关闭输入流和连接)

关于java - 如何通过 https URL 针对 XSD 验证 XML 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14269618/

相关文章:

java - onpostexecute 中 Intent 的上下文不为空但出现空异常

java - Android:编辑xml中定义的textview

java - java注解可以被覆盖吗?如果是这样?如何?

validation - Grails 为命令对象定义自定义错误消息

javascript - 仅当单击特定按钮时提交

java - 在 PVector 集上处理草图崩溃

java - java中如何声明数组为long类型?

java - Gson 反序列化期间使用 Dagger 进行依赖注入(inject)

xml - 为 log4net 设置动态连接字符串

c# - 给定的路径格式不支持 c#