欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

RestTemplate 使用

程序员文章站 2022-06-26 13:20:41
...

1. 项目中创建单例(当然也可以使用时创建实例)

@Configuration
public class RestTemplateConfig {
    @Bean(name = "factory")
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(15000);
        factory.setReadTimeout(5000);
        return factory;
    }
    
    @Bean(name = "restTemplate")
    public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
        return new RestTemplate(factory);
    }
}

1. GET请求

@Autowired
private RestTemplate restTemplate;
    
...
// 封装Header 一般来说不需要封装
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.add("", "keep-alive");

HttpEntity<String> requestEntity = new HttpEntity<>(null, requestHeaders);
                
// 根据不同的相应类型来接取
 ResponseEntity<String> entity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);

 ResponseEntity<Resource> entity = rest.exchange(matchUrl, HttpMethod.GET, requestEntity, Resource.class);
 
 ResponseEntity<Map> entity =  restTemplate.exchange(url,HttpMethod.GET,Resource,Map.class);
 
 

2. post请求

HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.add("Content-type", "application/json; charset=utf-8");
Map<String,Object> body = new HashMap<>();
body.put("id",1);
HttpEntity<Map> requestEntity = new HttpEntity<>(body, requestHeaders);
// 根据不同的相应类型来接取
 ResponseEntity<String> entity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);

 ResponseEntity<Resource> entity = rest.exchange(matchUrl, HttpMethod.POST, requestEntity, Resource.class);
 
 ResponseEntity<Map> entity =  restTemplate.exchange(url,HttpMethod.POST,Resource,Map.class);
相关标签: 后端