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

SpringBoot-RestTemplate配置

程序员文章站 2022-03-04 20:27:52
...

由于经常需要调用restful接口,特此记一下

1.配置实现类

@Configuration
public class RestTemplateConfig {

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

2.使用

@Service
public class TestService {
    @Autowired
    private RestTemplate restTemplate;


    //常规调用
    public String TestPost(String url) {
        //url = "http://****:****/*******";
        ResponseEntity<String> results = restTemplate.exchange(url, HttpMethod.POST, null, String.class);
        String json = results.getBody();
        return json;
    }

//传输JSON或者JSON数组,对象多层嵌套
    public String reserveCarReserve(String url, *** ***) {
        url = "http://****:****/****";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> map2 = new HashMap<>();
        map.put("***", ***);
        map.put("***", ***);
        map.put("***", ***);
        map.put("***", ***);

        map2.put("ReserveOrder",map);
        HttpEntity<Map<String, Object>> request = new HttpEntity<>(map2, headers);
        String json = restTemplate.postForEntity(url, request, String.class).getBody();
        return json;
    }

}

3.暂时没啥好补充的

相关标签: RestTemplate