这是我的休息控制器(服务器):
@RestController
public class RemoteController {
@RequestMapping(value="/test", method=RequestMethod.GET)
public Return serverTest(HttpServletRequest req, SearchFilter search) throws Exception{
//...
return new OutputTest();
}
}
我想用SearchFilter对象作为输入为这个GET控制器编写相应的客户端。
public void clientTest(){
SearchFilter input=new SearchFilter();
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = input;// how to store SearchFilter input ??????
ResponseEntity<OutputTest> response=restTemplate.exchange("http://localhost:8080/test", HttpMethod.GET, entity, OutputTest.class);
OutputTest out=response.getBody();
}
如何将单个对象发送到restTemplate?
答案 0 :(得分:1)
您应该告诉Spring如何将请求参数绑定到SearchFilter
。有多种方法可以实现这一点,最简单的解决方案是使用ModelAttribute
注释:
@RequestMapping(value="/test", method=RequestMethod.GET)
public Return serverTest(HttpServletRequest req, @ModelAttribute SearchFilter search) throws Exception{
//...
return new OutputTest();
}
假设您的SearchFilter
看起来像这样:
public class SearchFilter {
private String query;
// other filters and getters and setters
}
如果您向/test?query=something
发出请求,SearchFilter
将填充已发送的查询参数。要使用RestTemplate
发送此请求:
RestTemplate template = new RestTemplate();
// prepare headers
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
// request without body, just headers
HttpEntity<Object> request = new HttpEntity<>(headers);
ResponseEntity<OutputTest> response = template.exchange("http://localhost:8080/test?query=something",
HttpMethod.GET,
request,
OutputTest.class);
我能想到的另一种方法是实现HandlerMethodArgumentResolver
来解析SearchFilter
个参数。此外,您可以将SearchFilter
分开并使用多个RequestParam
。