RestClientException:无法写入请求:找不到请求类型

时间:2017-08-04 08:17:26

标签: java json rest spring-mvc resttemplate

我正在尝试使用RestTemplate访问POST REST服务但是得到以下错误estClientException:无法写入请求:没有为请求类型[xxx.query.XBrainQueryRequest]和内容类型[application / json]找到合适的HttpMessageConverter。 / p>

XBrainQueryRequest request = new XBrainQueryRequest();
// set query ID
request.setQueryId(XBrainTradequeryId);
request.setFlags(new String[]{"ALL_FIELDS"});
ObjectMapper objectMapper = new ObjectMapper();

logger.info("calling XBrainTradeQuery and  Input:{}",objectMapper.writeValueAsString(request));

HttpHeaders headers = new HttpHeaders();

headers.setContentType(MediaType.APPLICATION_JSON);

 try
       {
       restTemplate = new RestTemplate();

       ResponseEntity<XBrainTradeList> result=null;
       xBrainTradeList =null;

       ResponseEntity<XBrainTradeList> result1 = restTemplate.exchange(XBrainTradeQueryURL, HttpMethod.POST, new HttpEntity(request, headers), XBrainTradeList.class);

和我的XBrainQueryRequest类如下

@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class XBrainQueryRequest {

    private String queryId;
    private String[] flags;
    private String[] attributes;

    /**
     * @return the queryId
     */

    public String getQueryId() {
        return queryId;
    }

    public XBrainQueryRequest(String queryId, String[] flags, String[] attributes) {
        super();
        this.queryId = queryId;
        this.flags = flags;
        this.attributes = attributes;
    }

    public XBrainQueryRequest() {
    }

    public XBrainQueryRequest(String queryId, String[] flags) {
        super();
        this.queryId = queryId;
        this.flags = flags;
    }

    /**
     * @param queryId
     *            the queryId to set
     */
    public void setQueryId(String queryId) {
        this.queryId = queryId;
    }

    public String[] getFlags() {
        return flags;
    }

    public void setFlags(String[] flags) {
        this.flags = flags;
    }

    public String[] getAttributes() {
        return attributes;
    }

    public void setAttributes(String[] attributes) {
        this.attributes = attributes;
    }

}

有人可以解释我为什么会收到错误以及如何解决错误。我是这些东西的新手。

2 个答案:

答案 0 :(得分:1)

解决。用objectMapper.writeValueAsString(request)替换了请求参数。请求值存在JSON格式问题。

旧代码

ResponseEntity<XBrainTradeList> result1 =
    restTemplate.exchange(
        XBrainTradeQueryURL,
        HttpMethod.POST,
        new HttpEntity(request, headers),
        XBrainTradeList.class);

新代码

ResponseEntity<String> rest= 
    restTemplate.exchange(
        XBrainTradeQueryURL,
        HttpMethod.POST, 
        new HttpEntity(objectMapper.writeValueAsString(request), headers), 
        String.class);

此外,我已采用String格式的回复。

答案 1 :(得分:0)

检查spring-web依赖版本,我改成最新的(5.3.5),对我有用!

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>5.3.5</version>
    </dependency>