我调用第三方提供的旧网络服务。我正在使用春天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>
The 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 https://xerces.apache.org/xerces2-j/features.html#disallow-doctype-decl
问题:如何在不完全避免 Spring RestTemplate 的自动行为的情况下自定义解组?我想强制解组器接受包含具有 DTD 引用的元素的 XML。
这个问题与我的另一个问题密切相关如何在 Spring RestTemplate 中自定义自动封送处理以生成/修改 XML 标头(编码、DOCTYPE) https://stackoverflow.com/q/47836310/2886891,但是那里提出的解决方案在这里并不容易适用。