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