using resttemplate to call rest service code example

Example 1: resttemplate get rest api call in java

private static void getEmployees()
{
    final String uri = "http://localhost:8080/springrestexample/employees";
 
    //TODO: Autowire the RestTemplate in all the examples
    RestTemplate restTemplate = new RestTemplate();
 
    String result = restTemplate.getForObject(uri, String.class);
    System.out.println(result);
}

Example 2: resttemplate get rest api call in java

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
 
    return builder
            .setConnectTimeout(Duration.ofMillis(3000))
            .setReadTimeout(Duration.ofMillis(3000))
            .build();
}

Example 3: resttemplate get rest api call in java

private static void getEmployees()
{
    final String uri = "http://localhost:8080/springrestexample/employees";
    RestTemplate restTemplate = new RestTemplate();
     
    EmployeeListVO result = restTemplate.getForObject(uri, EmployeeListVO.class);
     
    //Use the response
}

Example 4: resttemplate get rest api call in java

@Autowired
CloseableHttpClient httpClient;
 
@Bean
public RestTemplate restTemplate() {
 
    RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory());
    return restTemplate;
}
 
@Bean
public HttpComponentsClientHttpRequestFactory clientHttpRequestFactory() {
 
    HttpComponentsClientHttpRequestFactory clientHttpRequestFactory 
                            = new HttpComponentsClientHttpRequestFactory();
    clientHttpRequestFactory.setHttpClient(httpClient);
    return clientHttpRequestFactory;
}

Tags:

Java Example