使用 Spring RestTemplate 和自定义对象输入参数的 Rest 客户端

Rest client with Spring RestTemplate and custom Object input parameter

这是我的休息控制器(服务器):

@RestController
public class RemoteController {

    @RequestMapping(value="/test", method=RequestMethod.GET)  
    public Return serverTest(HttpServletRequest req, SearchFilter search) throws Exception{
        //...
        return new OutputTest();
    }
}

我想为这个 GET 控制器编写相应的客户端,并将 SearchFilter 对象作为输入。

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?

你应该告诉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