接受Hashmap作为POST调用的正文

时间:2019-08-14 05:14:56

标签: spring resttemplate

我必须编写一个程序,该程序将接受Hashmap格式的主体。 我用Hashmap值和标头创建了HttpEntity。

public <T> void doPOSTRequest(String url, T body, HttpHeaders headers) throws JsonProcessingException {

    HttpEntity<T> request = new HttpEntity<T>(body,headers);
    System.out.println("Printing Request :" + request);
    ResponseEntity<String> response = null;

    //Calling POST Method
    //response=restTemplate.postForObject(url,request,String.class);
     response=restTemplate.exchange(url, HttpMethod.POST,request,String.class);


    System.out.println(response);

}

我正面临以下异常:

  

线程“主”中的异常   org.springframework.web.client.RestClientException:否   用于[java.util.HashMap]的HttpMessageConverter,位于   org.springframework.web.client.RestTemplate $ HttpEntityRequestCallback.doWithRequest(RestTemplate.java:957)     在   org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:733)     在   org.springframework.web.client.RestTemplate.execute(RestTemplate.java:670)     在   org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:579)     在Com.RESTRequest.doPOSTRequest(RESTRequest.java:39)在   Com.GenericREST.main(GenericREST.java:30)

1 个答案:

答案 0 :(得分:0)

尝试使用MultiValueMap代替通用

HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<MultiValueMap<String, Object>>(parameters, headers);

完整块:

public <T> void doPOSTRequest(String url, T body, HttpHeaders headers) throws JsonProcessingException {
    HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<MultiValueMap<String, Object>>(body,headers);
    System.out.println("Printing Request :" + request);
    ResponseEntity<String> response = null;
    //Calling POST Method
    //response=restTemplate.postForObject(url,request,String.class);
     response=restTemplate.exchange(url, HttpMethod.POST,request,String.class);

    System.out.println(response);
}