【发布时间】:2018-05-30 22:41:23
【问题描述】:
我调用了第三方提供的旧网络服务。我正在使用 Spring RestTemplate:
HttpEntity<MyRequest> requestHttpEntity = new HttpEntity<>(requestBody, headers);
MyResponse response = restTemplate.postForEntity(url, requestHttpEntity, MyResponse.class);
我收到一个 XML(我无法影响的格式,它是第三方服务)作为响应:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE MyResponse SYSTEM "http://example.com:8080/some/path/MyResponse.dtd">
<MyResponse>
...
</MyResponse>
postForEntity() 方法抛出异常
org.springframework.web.client.RestClientException:
Error while extracting response for type [class com.example.MyResponse] and content type [text/xml;charset=ISO-8859-1];
nested exception is org.springframework.http.converter.HttpMessageNotReadableException:
Could not unmarshal to [class com.example.MyResponse]: null;
nested exception is javax.xml.bind.UnmarshalException
- with linked exception:
[org.xml.sax.SAXParseException; lineNumber: 2; columnNumber: 10;
DOCTYPE is disallowed when the feature
"http://apache.org/xml/features/disallow-doctype-decl" set to true.]
我在这里找到了对 http://apache.org/xml/features/disallow-doctype-decl 功能的唯一合理参考:https://xerces.apache.org/xerces2-j/features.html#disallow-doctype-decl
问题:如何在不完全避免 Spring RestTemplate 的自动行为的情况下自定义解组?我想强制解组器接受包含带有 DTD 引用的 XML 元素。
这个问题与我的另一个问题How to customize automatic marshaling in Spring RestTemplate to produce/modify XML headers (encoding, DOCTYPE) 密切相关,但那里提出的解决方案在这里并不容易适用。
【问题讨论】:
-
只需将该属性设置为 false... 您可以将
HttpMessageConverter配置为这样做 docs.spring.io/spring/docs/current/javadoc-api/org/… 。默认情况下,此属性设置为false禁用 DTD 支持,这与启用 DTD 支持时的安全隐患有关。 -
@M.Deinum 它就像魔术一样工作(假设您的意思是将该属性设置为 true :)),谢谢!我以前没有注意到这个方法。请给它一个答案,我很乐意接受它!你对我的相关问题stackoverflow.com/q/47836310/2886891也有这么简单的答案吗? Alex Savitsky 的回答确实有效,但对我来说更像是一个 hack。
-
在此处查看答案,尤其是第二部分也应该回答您的其他问题。
标签: java xml spring unmarshalling resttemplate