HTTP get with headers using RestTemplate

The RestTemplate getForObject() method does not support setting headers. The solution is to use the exchange() method. So instead of restTemplate.getForObject(url, String.class, param) (which has no headers), use HttpHeaders headers = new HttpHeaders(); headers.set(“Header”, “value”); headers.set(“Other-Header”, “othervalue”); … HttpEntity<Void> requestEntity = new HttpEntity<>(headers); ResponseEntity<String> response = restTemplate.exchange( url, HttpMethod.GET, requestEntity, String.class, param); Finally, use response.getBody() … Read more

Disabling SSL Certificate Validation in Spring RestTemplate

@Bean public RestTemplate restTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException { TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true; SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom() .loadTrustMaterial(null, acceptingTrustStrategy) .build(); SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext); CloseableHttpClient httpClient = HttpClients.custom() .setSSLSocketFactory(csf) .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); requestFactory.setHttpClient(httpClient); RestTemplate restTemplate = new RestTemplate(requestFactory); return restTemplate; }

Spring Resttemplate exception handling

You want to create a class that implements ResponseErrorHandler and then use an instance of it to set the error handling of your rest template: public class MyErrorHandler implements ResponseErrorHandler { @Override public void handleError(ClientHttpResponse response) throws IOException { // your error handling here } @Override public boolean hasError(ClientHttpResponse response) throws IOException { … } … Read more

Spring RestTemplate timeout

For Spring Boot >= 1.4 @Configuration public class AppConfig { @Bean public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) { return restTemplateBuilder .setConnectTimeout(…) .setReadTimeout(…) .build(); } } For Spring Boot <= 1.3 @Configuration public class AppConfig { @Bean @ConfigurationProperties(prefix = “custom.rest.connection”) public HttpComponentsClientHttpRequestFactory customHttpRequestFactory() { return new HttpComponentsClientHttpRequestFactory(); } @Bean public RestTemplate customRestTemplate() { return new RestTemplate(customHttpRequestFactory()); } } … Read more

Could not autowire field:RestTemplate in Spring boot application

It’s exactly what the error says. You didn’t create any RestTemplate bean, so it can’t autowire any. If you need a RestTemplate you’ll have to provide one. For example, add the following to TestMicroServiceApplication.java: @Bean public RestTemplate restTemplate() { return new RestTemplate(); } Since Spring boot 1.4, there’s also a convenient builder that you can … Read more

How to POST form data with Spring RestTemplate?

The POST method should be sent along the HTTP request object. And the request may contain either of HTTP header or HTTP body or both. Hence let’s create an HTTP entity and send the headers and parameter in body. HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>(); map.add(“email”, “first.last@example.com”); HttpEntity<MultiValueMap<String, String>> … Read more

Get list of JSON objects with Spring RestTemplate

First define an object to hold the entity coming back in the array.. e.g. @JsonIgnoreProperties(ignoreUnknown = true) public class Rate { private String name; private String code; private Double rate; // add getters and setters } Then you can consume the service and get a strongly typed list via: ResponseEntity<List<Rate>> rateResponse = restTemplate.exchange(“https://bitpay.com/api/rates”, HttpMethod.GET, null, … Read more

How to set an “Accept:” header on Spring RestTemplate request?

I suggest using one of the exchange methods that accepts an HttpEntity for which you can also set the HttpHeaders. (You can also specify the HTTP method you want to use.) For example, RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); HttpEntity<String> entity = new HttpEntity<>(“body”, headers); restTemplate.exchange(url, HttpMethod.POST, entity, String.class); I … Read more

Spring RestTemplate – how to enable full debugging/logging of requests/responses?

Just to complete the example with a full implementation of ClientHttpRequestInterceptor to trace request and response: import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpRequest; import org.springframework.http.client.ClientHttpRequestExecution; import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.http.client.ClientHttpResponse; public class LoggingRequestInterceptor implements ClientHttpRequestInterceptor { final static Logger log = LoggerFactory.getLogger(LoggingRequestInterceptor.class); @Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) … Read more

error code: 521