【问题标题】:Accepting Hashmap as a body for the POST call接受 Hashmap 作为 POST 调用的主体
【发布时间】:2023-03-19 22:00:02
【问题描述】:

我必须编写一个程序来接受 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);

}

我面临以下异常:

线程“main”中的异常 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)

【问题讨论】:

    标签: spring resttemplate


    【解决方案1】:

    尝试使用MultiValueMap,而不是像这样的 Generic

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

    【讨论】:

    • 感谢您的回复。但我将 Map 作为输入参数。由于依赖关系,我无法更改它。
    • 那么在这种情况下,请查看为 POST 请求标头 W 传递的内容类型
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-12
    • 1970-01-01
    • 2022-01-13
    相关资源
    最近更新 更多