我正在处理的当前项目涉及从Java应用程序调用许多Web服务。 Web服务托管在运行在虚拟化Linux机器上的payara / glassfish服务器上。 Web服务从两个不同的旧系统返回数据,一个基于SQLServer数据库,另一个基于FoxPro数据库。
有时,Web服务将返回包含xml版本1.0不允许的值(字节)的数据,并且应用程序将引发解组异常,响应中的无效字符(0x2)。
由于我无法控制从数据库中获取的数据,因此我需要找到一种方法来过滤/替换有问题的字符,以便应用程序可以使用该数据。
我确实可以访问Web服务代码,因此可以根据需要更改服务和客户端。
我确实读过xml版本1.1允许某些控制字符的地方,但是我不确定如何升级该版本,甚至不确定在哪里进行升级。
有什么建议吗?
最佳答案
像本教程(https://dennis-xlc.gitbooks.io/restful-java-with-jax-rs-2-0-2rd-edition/content/en/part1/chapter6/custom_marshalling.html)一样,您可以通过从readFrom
接口实现MessageBodyReader
来制作自定义解组器,如下所示:
Object readFrom(Class<Object>, Type genericType,
Annotation annotations[], MediaType mediaType,
MultivaluedMap<String, String> httpHeaders,
InputStream entityStream)
throws IOException, WebApplicationException {
try {
JAXBContext ctx = JAXBContext.newInstance(type);
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();
// replace all special characters
theString = theString.replaceAll("[\u0000-\u001f]", "");
return ctx.createUnmarshaller().unmarshal(theString);
} catch (JAXBException ex) {
throw new RuntimeException(ex);
}
}
关于java - Web服务和解码异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42029078/