【发布时间】:2016-11-09 06:50:15
【问题描述】:
如何使用 RestTemplate 将对象作为参数传入?例如,假设我使用 Spring Boot 设置了以下服务:
@RequestMapping(value = "/get1", method = RequestMethod.GET)
public ResponseEntity<String> get1(@RequestParam(value = "parm") String parm) {
String response = "You entered " + parm;
return new ResponseEntity<String>(response, HttpStatus.OK);
}
@RequestMapping(value = "/get2", method = RequestMethod.GET)
public ResponseEntity<String> get2(@RequestParam(value = "parm") MyObj parm) {
String response = "You entered " + parm.getValue();
return new ResponseEntity<String>(response, HttpStatus.OK);
}
如果客户想要调用第一个服务,他们可以使用以下方法:
//This works fine
RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject("http://localhost:8080/get1?parm={parm}", String.class, "Test input 1");
但如果客户想要调用第二个服务,他们会使用以下内容得到 500 错误:
//This doesn't work
MyObj myObj = new MyObj("Test input 2");
RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject("http://localhost:8080/get2?parm={parm}", String.class, myObj);
MyObj 类如下所示:
@JsonSerialize
public class MyObj {
private String inputValue;
public MyObj() {
}
public MyObj(String inputValue) {
this.inputValue = inputValue;
}
public String getInputValue() {
return inputValue;
}
public void setInputValue(String inputValue) {
this.inputValue = inputValue;
}
}
我假设问题在于 myObj 没有正确设置为参数。我该怎么做?
提前致谢。
【问题讨论】:
标签: java spring spring-boot get resttemplate