由於經常需要調用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; } }