RestTemplate:没有合适的HttpMessageConverter发现异常

时间:2017-08-14 13:06:12

标签: java xml spring spring-boot resttemplate

我试图在spring boot中解析以下xml响应:

响应结构:

1742 weighted sum: 1774442222

来自服务的Api电话:

<!DOCTYPE RESULT SYSTEM 'http://www.example.com/example/exampleV1.00.dtd'>
<RESULT REQID ='10961549902'>
    <MID SUBMITDATE='2017-08-14 17:17:29' ID='1' TAG = 'null' TID = '24180566483'></MID>
</RESULT>

ResponseXml.java

RestTemplate restTemplate = new RestTemplate();    
restTemplate.getForObject("http://www.exampleUrl.com",ResponseXml.class);

抛出异常:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "RESULT")
public class ResponseXml implements Serializable{

    @XmlAttribute(name="REQID")
    private long requestId;

    @XmlElement(name = "MID")
    private long MID;

    public ResponseXml() {
      super();
    }

    public ResponseXml(long requestId) {
      super();
      this.requestId = requestId;
    }

    //getter setter

    public class MID {

    @XmlAttribute(name="SUBMITDATE")
    private Date submitDate;
    @XmlAttribute(name="ID")
    private Long id;
    @XmlAttribute(name="TAG")
    private Long tag;
    @XmlAttribute(name="TID")
    private Long tid;

    //getter setter
  }
}

请提出修复建议,如何在JAVA spring boot中解析xml响应? 尽管添加了@XmlRootElement注释,为什么我会收到HttpMessageConverter异常?

1 个答案:

答案 0 :(得分:1)

如果无法修复服务器,请配置在客户端应用程序中转换的邮件以接受plain/text

// Create converter which supports text/plain mime type.
MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
List<MediaType> mediaTypes = jsonConverter.getSupportedMediaTypes();
mediaTypes.add(MediaType.TEXT_PLAIN);
jsonConverter.setSupportedMediaTypes(mediaTypes);

// Alternatively get mapper as injected bean:
// @Inject
// private XmlMapper mapper;
XmlMapper mapper = new XmlMapper();
jsonConverter.setObjectMapper(mapper);

RestTemplate restTemplate = new RestTemplate();
// Register converter with RestTemplate
restTemplate.setMessageConverters(Arrays.asList(jsonConverter));