gpt4 book ai didi

java - RestTemplate:没有找到合适的 HttpMessageConverter 异常

转载 作者:行者123 更新时间:2023-11-30 06:33:13 29 4
gpt4 key购买 nike

我正在尝试在 Spring Boot 中解析以下 xml 响应:

响应结构:

<!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>

来自服务的 API 调用:

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

ResponseXml.java

@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
}
}

抛出异常:

Method threw 'org.springframework.web.client.RestClientException' exception.

Detailed message: Could not extract response: no suitable HttpMessageConverter found
for response type [class com.hk.response.sms.NetcoreResponseXml]
and content type [text/plain;charset=UTF-8]

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

最佳答案

如果无法修复服务器,则配置在客户端应用程序中转换的消息以接受纯文本/文本:

// 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));

关于java - RestTemplate:没有找到合适的 HttpMessageConverter 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45675216/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com