Questions tagged [resttemplate]

Use this tag for Spring's RestTemplate, a class for client-side HTTP communications and RESTful principles enforcement.

The RestTemplate is the central Spring class for client-side HTTP access. Conceptually, it is very similar to the JdbcTemplate, JmsTemplate, and the various other templates found in the Spring Framework and other portfolio projects.

This means, for instance, that the RestTemplate is thread-safe once constructed, and that you can use callbacks to customize its operations.

RestTemplate Methods

-------------------------------------------------------------
| HTTP          | RESTTEMPLATE                               |
-------------------------------------------------------------
| DELETE        | delete(String, String...)                  |
-------------------------------------------------------------
| GET           | getForObject(String, Class, String...)     | 
-------------------------------------------------------------
| HEAD          | headForHeaders(String, String...)          | 
-------------------------------------------------------------
| OPTIONS       | optionsForAllow(String, String...)         | 
-------------------------------------------------------------
| POST          | postForLocation(String, Object, String...) | 
-------------------------------------------------------------
| PUT           | put(String, Object, String...)             | 
-------------------------------------------------------------

Reference: https://spring.io/blog/2009/03/27/rest-in-spring-3-resttemplate

Error Handling and Customization of Errors

Implement and inject the ResponseErrorHandler interface in a RestTemplate instance – to gracefully handle HTTP errors returned by remote APIs.

By default, the RestTemplate will throw one of these exceptions in case of an HTTP error:

  • HttpClientErrorException – in case of HTTP status 4xx
  • HttpServerErrorException – in case of HTTP status 5xx
  • UnknownHttpStatusCodeException – in case of an unknown HTTP status

One Can configure a Spring RestTemplate bean as well

  • using the default RestTemplateBuilder
  • using a RestTemplateCustomizer
  • creating RestTemplateBuilder
2832 questions
40
votes
1 answer

Setting request header content-type to json in Spring Framework resttemplate

I'm learning Spring Framework to create a client of a REST web service that uses basic authentication and exchanges JSON. After much searching on the web, I wrote some code that worked (below), but now I'm getting an "Unsupported Media Type" error…
user2752012
  • 413
  • 1
  • 4
  • 7
40
votes
3 answers

How to parse the response body in Java, when the HTTP request has return status 401

I am consuming a RESTful JSON API using Spring's RestTemplate and Jackson. In some cases we may receive a Status 401 (Unauthorized) response with a custom JSON body, that is defined by the API manufacturer, and looks like this: { "code": 123, …
Ivaylo Slavov
  • 8,839
  • 12
  • 65
  • 108
40
votes
5 answers

Could not read JSON: Can not deserialize instance of hello.Country[] out of START_OBJECT token

I have rest url that gives me all countries - http://api.geonames.org/countryInfoJSON?username=volodiaL. I use RestTemplate from spring 3 to parse returned json into java objects: RestTemplate restTemplate = new RestTemplate(); Country[] countries =…
Volodymyr Levytskyi
  • 3,364
  • 9
  • 46
  • 83
37
votes
9 answers

RestTemplate client with cookies

I'm writing a simple client in Java to allow reusable use of proprietary virus scanning software accessible through a RESTful API. To upload a file for scanning the API requires a POST for Connect, followed by a POST for Publishing the file to the…
Tom
  • 3,006
  • 6
  • 33
  • 54
36
votes
2 answers

Why do I always get 403 when fetching data with RestTemplate?

I'm trying to fetch data but always getting 403(Forbidden) with RestTemplate. But when I try org.apache.http.client.HttpClient instead, everything is OK. I'm also able to get data with Postman on my machine. The code is quite simple but I don't know…
Kanjie Lu
  • 997
  • 2
  • 9
  • 26
34
votes
4 answers

Retry java RestTemplate HTTP request if host offline

Hi I'm using the spring RestTemplate for calling a REST API. The API can be very slow or even offline. My application is building the cache by sending thousands of requests one after the other. The responses can be very slow too, because they…
Robert Moszczynski
  • 1,081
  • 2
  • 16
  • 26
32
votes
7 answers

resttemplate getForObject map responsetype

Update 02/05/2018 (about 4 years later)...I tested this again as people have been upvoting my question/answer and Sotirios Delimanolis is correct that I should not have to write the code in my answer to make this work. I used basically the same…
Zack Macomber
  • 6,682
  • 14
  • 57
  • 104
31
votes
3 answers

RestTemplate - Handling response headers/body in Exceptions (RestClientException, HttpStatusCodeException)

In my restful webservice, in case of bad request (5xx) or 4xx respose codes, I write a custom header "x-app-err-id" to the response. On the client side, I use exchange method of RestTemplate to make a RestFul web service call. Everything is fine…
Chandra
  • 1,577
  • 3
  • 21
  • 28
31
votes
2 answers

What is the right way to send a client certificate with every request made by the resttemplate in spring?

i want to consume a REST service with my spring application. To access that service i have a client certificate (self signed and in .jks format) for authorization. What is the proper way to authenticate against the rest service? This is my…
31
votes
4 answers

Follow 302 redirect using Spring restTemplate?

RestTemplate restTemplate = new RestTemplate(); final MappingJackson2XmlHttpMessageConverter converter = new MappingJackson2XmlHttpMessageConverter(); final List supportedMediaTypes = new…
techie.brandon
  • 1,638
  • 2
  • 18
  • 27
31
votes
6 answers

Java Spring resttemplate character encoding

I'm using the Java Spring Resttemplate for getting a json via a get request. The JSON I'm getting has instead of special character slike ü ö ä or ß some weird stuff. So I guess somethings wrong with the character encoding. I can't find any help on…
Shachty
  • 521
  • 2
  • 7
  • 16
31
votes
4 answers

REST client restTemplate can't get Collection of objects

I use Spring restTemplate. I made a REST service and client as unit test in separated application. I have method that return List of users and method for user creating: @GET @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, …
Oleksandr H
  • 2,965
  • 10
  • 40
  • 58
31
votes
5 answers

Spring RestTemplate invoking webservice with errors and analyze status code

I designed a webservice to perform a task if request parameters are OK, or return 401 Unauthorized HTTP status code if request parameters are wrong or empty. I'm using RestTemplate to perform a test and I'm able to verify the HTTP 200 OK status if…
Premier
  • 4,160
  • 6
  • 44
  • 58
30
votes
4 answers

How to set multiple headers at once in Spring WebClient?

I was trying to set headers to my rest client but every time I have to write webclient.get().uri("blah-blah") .header("key1", "value1") .header("key2", "value2")... How can I set all headers at the same time using headers()…
30
votes
4 answers

How to unittest a class using RestTemplate offline?

I have a class which has direct dependency on the RestTemplate. I wish I have a JUnit test of it, offline. How could I mock a RestTemplate in my unittest?
Dennis C
  • 24,511
  • 12
  • 71
  • 99