我需要使用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。请求生成失败。
有人能帮我找到办法吗?我可以简单地传递一个没有问题的字符串对象。用户定义的对象会产生问题。
感谢任何帮助!!!
答案 0 :(得分:31)
You can do it fairly simply with 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);
上面的链接应告诉您如何根据需要进行设置。这是一个非常好的教程。
答案 1 :(得分:1)
在RestController中接收NewObject
@PostMapping("/create") public ResponseEntity<String> createNewObject(@RequestBody NewObject newObject) { // do your stuff}
答案 2 :(得分: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;
}