Spring MVC – RestTemplate launch exception when http 404 happens

As far as I’m aware, you can’t get an actual ResponseEntity, but the status code and body (if any) can be obtained from the exception: try { ResponseEntity<StoreDto> r = restTemplate.getForEntity(url, StoreDto.class, m); } catch (final HttpClientErrorException e) { System.out.println(e.getStatusCode()); System.out.println(e.getResponseBodyAsString()); }

RestTemplate vs Apache Http Client for production code in spring project

RestTemplate and HttpClient don’t operate at the same abstraction level. HttpClient is a general-purpose library to communicate using HTTP, whereas RestTemplate is a higher-level abstraction, dealing with JSON/XML transformation of entities, etc. RestTemplate delegates to a ClientHttpRequestFactory, and one of the implementations of this interface uses Apache’s HttpClient. So, if the goal is to communicate … Read more

RestTemplate: How to send URL and query parameters together

I would use buildAndExpand from UriComponentsBuilder to pass all types of URI parameters. For example: String url = “http://test.com/solarSystem/planets/{planet}/moons/{moon}”; // URI (URL) parameters Map<String, String> urlParams = new HashMap<>(); urlParams.put(“planet”, “Mars”); urlParams.put(“moon”, “Phobos”); // Query parameters UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url) // Add query parameter .queryParam(“firstName”, “Mark”) .queryParam(“lastName”, “Watney”); System.out.println(builder.buildAndExpand(urlParams).toUri()); /** * Console output: * http://test.com/solarSystem/planets/Mars/moons/Phobos?firstName=Mark&lastName=Watney … Read more

How to forward large files with RestTemplate?

Edit: The other answers are better (use Resource) https://stackoverflow.com/a/36226006/116509 My original answer: You can use execute for this kind of low-level operation. In this snippet I’ve used Commons IO’s copy method to copy the input stream. You would need to customize the HttpMessageConverterExtractor for the kind of response you’re expecting. final InputStream fis = new … Read more

How do I read the response header from RestTemplate?

Ok, I finally figured it out. The exchange method is exactly what i need. It returns an HttpEntity which contains the full headers. RestTemplate template = new RestTemplate(); HttpEntity<String> response = template.exchange(url, HttpMethod.POST, request, String.class); String resultString = response.getBody(); HttpHeaders headers = response.getHeaders();

Spring RestTemplate with paginated API

When migrating from Spring Boot 1.x to 2.0, changed the code reading the Rest API response as import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.JsonNode; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import java.util.ArrayList; import java.util.List; public class RestPageImpl<T> extends PageImpl<T>{ @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) public RestPageImpl(@JsonProperty(“content”) List<T> content, @JsonProperty(“number”) int number, @JsonProperty(“size”) int size, @JsonProperty(“totalElements”) Long totalElements, @JsonProperty(“pageable”) … Read more

How to send Multipart form data with restTemplate Spring-mvc

Reading the whole file in a ByteArrayResource can be a memory consumption issue with large files. You can proxy a file upload in a spring mvc controller using a InputStreamResource: @RequestMapping(value = “/upload”, method = RequestMethod.POST) public ResponseEntity<?> uploadImages(@RequestPart(“images”) final MultipartFile[] files) throws IOException { LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>(); String response; HttpStatus httpStatus … Read more

Sending Multipart File as POST parameters with RestTemplate requests

A way to solve this without needing to use a FileSystemResource that requires a file on disk, is to use a ByteArrayResource, that way you can send a byte array in your post (this code works with Spring 3.2.3): MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>(); final String filename=”somefile.txt”; map.add(“name”, filename); map.add(“filename”, filename); ByteArrayResource contentsAsResource … Read more

How do I retrieve HTTP status code and response body when an RestClientException is thrown?

Instead of catching RestClientException, catch the special HttpClientErrorException. Here’s an example: try { Link dataCenterLink = serviceInstance.getLink(“dataCenter”); String dataCenterUrl = dataCenterLink.getHref(); DataCenterResource dataCenter = restTemplate.getForObject(dataCenterUrl, DataCenterResource.class); serviceInstance.setDataCenter(dataCenter); } catch (HttpClientErrorException e) { HttpStatus status = e.getStatusCode(); if (status != HttpStatus.NOT_FOUND) { throw e; } } HttpClientErrorException provides getStatusCode and getResponseBodyAsByteArray to get the status code … Read more

ClassCastException: RestTemplate returning List instead of List

With the following method call List<MyModelClass> myModelClass=(List<MyModelClass>) restTemplate.postForObject(url,mvm,List.class); All Jackson knows is that you want a List, but doesn’t have any restriction on the type. By default Jackson deserializes a JSON object into a LinkedHashMap, so that’s why you are getting the ClassCastException. If your returned JSON is an array, one way to get it … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)