13

我需要使用 RESTTemplate 将自定义对象传递给我的 REST 服务。

RestTemplate restTemplate = new RestTemplate();
MultiValueMap<String, Object> requestMap = new LinkedMultiValueMap<String, Object>();
...

requestMap.add("file1", new FileSystemResource(..);
requestMap.add("Content-Type","text/html");
requestMap.add("accept", "text/html");
requestMap.add("myobject",new CustomObject()); // This is not working
System.out.println("Before Posting Request........");
restTemplate.postForLocation(url, requestMap);//Posting the data.
System.out.println("Request has been executed........");

我无法将自定义对象添加到 MultiValueMap。请求生成失败。

有人可以帮我找到解决方法吗?我可以简单地传递一个字符串对象而不会出现问题。用户定义的对象会造成问题。

感谢任何帮助!

4

3 回答 3

34

您可以使用 Jackson 相当简单地做到这一点

这是我为一个简单 POJO 的帖子所写的内容。

@XmlRootElement(name="newobject")
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class NewObject{
    private String stuff;

    public String getStuff(){
        return this.stuff;
    }

    public void setStuff(String stuff){
        this.stuff = stuff;
    }
}

....
//make the object
NewObject obj = new NewObject();
obj.setStuff("stuff");

//set your headers
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);

//set your entity to send
HttpEntity entity = new HttpEntity(obj,headers);

// send it!
ResponseEntity<String> out = restTemplate.exchange("url", HttpMethod.POST, entity
    , String.class);

上面的链接应该告诉您如何在需要时进行设置。它是一个很好的教程。

于 2012-06-20T14:34:14.357 回答
0

在 RestController 中接收 NewObject

@PostMapping("/create") public ResponseEntity<String> createNewObject(@RequestBody NewObject newObject) { // do your stuff}
于 2016-10-05T06:55:48.360 回答
0

你可以试试这个

 public int insertParametro(Parametros parametro) throws LlamadasWSBOException {
        String metodo = "insertParam";
        String URL_WS = URL_WS_BASE + metodo;

        Integer request = null;

        try {
            logger.info("URL_WS: " + URL_WS);

            request = restTemplate.postForObject(URL_WS, parametro, Integer.class);

        } catch (RestClientResponseException rre) {
            logger.error("RestClientResponseException insertParametro [WS BO]: " + rre.getResponseBodyAsString());
            logger.error("RestClientResponseException insertParametro [WS BO]: ", rre);
            throw new CallWSBOException(rre.getResponseBodyAsString());
        } catch (Exception e) {
            logger.error("Exception insertParametro[WS BO]: ", e);
            throw new CallWSBOException(e.getMessage());
        }
        return request;
    }
于 2017-11-07T22:49:12.580 回答