SpringBoot-RestTemplate配置


由于经常需要调用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;
    }
 
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM