Reputation: 9506
This is my rest controller (server):
@RestController
public class RemoteController {
@RequestMapping(value="/test", method=RequestMethod.GET)
public Return serverTest(HttpServletRequest req, SearchFilter search) throws Exception{
//...
return new OutputTest();
}
}
I want to write the corresponding client for this GET controller with SearchFilter object as input.
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();
}
How can I send a single object to restTemplate?
Upvotes: 1
Views: 2371
Reputation: 48123
You should tell Spring how to bind the request parameters to SearchFilter
. There are multiple approachs to achieve that, The simplest solution is to use ModelAttribute
annotation:
@RequestMapping(value="/test", method=RequestMethod.GET)
public Return serverTest(HttpServletRequest req, @ModelAttribute SearchFilter search) throws Exception{
//...
return new OutputTest();
}
Supposing your SearchFilter
looks like this:
public class SearchFilter {
private String query;
// other filters and getters and setters
}
If you fire a request to /test?query=something
, the SearchFilter
will be populated with the sent query parameter. In order to send this request with 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);
The other approach i can think of, is to implement a HandlerMethodArgumentResolver
for resolving SearchFilter
arguments. Also, you can break the SearchFilter
apart and use multiple RequestParam
s.
Upvotes: 1