Java Spring—使用HttpEntity从ResponseEntity获取主体的通用方法

Java Spring—使用HttpEntity从ResponseEntity获取主体的通用方法,java,spring,httpentity,Java,Spring,Httpentity,在我的代码中,我经常以以下方式使用HttpEntity和ResponseEntity: HttpEntity<?> request = new HttpEntity<String>(myObject, headers); ResponseEntity<String> response = restTemplate.exchange("someurl", HttpMethod.POST, request, String.class); 我一直在重复这段代码,

在我的代码中,我经常以以下方式使用HttpEntity和ResponseEntity:

HttpEntity<?> request = new HttpEntity<String>(myObject, headers);

ResponseEntity<String> response = restTemplate.exchange("someurl", HttpMethod.POST, request, String.class);
我一直在重复这段代码,我想知道是否有可能创建一个通用方法,当我向它提供我想要发送的对象、url和HttpMethod类型时,该方法允许我获取response.body()。
大多数情况下,响应正文是字符串,但也可以是对象。

您可以使用以下代码,这里的响应正文和请求正文是通用的:

public <T, R> T yourMethodName(R requestBody, 
                               MultiValueMap<String, String> headers, 
                               String url, 
                               HttpMethod type, 
                               Class<T> clazz) {
    HttpEntity<?> request = new HttpEntity<String>(requestBody, headers);
   //You have to create restemplate Obj somewhere
    ResponseEntity<T> response = restTemplate.exchange(url, type, request, clazz);
    return response.getBody();
}
public T您的方法名(R请求主体,
多值映射头,
字符串url,
HttpMethod类型,
课程名称(clazz){
HttpEntity请求=新的HttpEntity(请求主体,标题);
//您必须在某处创建重新模板Obj
ResponseEntity response=restemplate.exchange(url、类型、请求、clazz);
返回response.getBody();
}

您可以使用以下代码,这里的响应正文和请求正文是通用的:

public <T, R> T yourMethodName(R requestBody, 
                               MultiValueMap<String, String> headers, 
                               String url, 
                               HttpMethod type, 
                               Class<T> clazz) {
    HttpEntity<?> request = new HttpEntity<String>(requestBody, headers);
   //You have to create restemplate Obj somewhere
    ResponseEntity<T> response = restTemplate.exchange(url, type, request, clazz);
    return response.getBody();
}
public T您的方法名(R请求主体,
多值映射头,
字符串url,
HttpMethod类型,
课程名称(clazz){
HttpEntity请求=新的HttpEntity(请求主体,标题);
//您必须在某处创建重新模板Obj
ResponseEntity response=restemplate.exchange(url、类型、请求、clazz);
返回response.getBody();
}