Nick Daugherty Nick Daugherty - 2 months ago 31
Java Question

Making authenticated POST requests with Spring RestTemplate for Android

I have a RESTful API I'm trying to connect with via Android and RestTemplate. All requests to the API are authenticated with HTTP Authentication, through setting the headers of the HttpEntity and then using RestTemplate's


All GET requests work great this way, but I cannot figure out how to accomplish authenticated POST requests.
handle POSTs, but have no easy way to set the Authentication headers.

So for GETs, this works great:

HttpAuthentication httpAuthentication = new HttpBasicAuthentication("username", "password");
HttpHeaders requestHeaders = new HttpHeaders();

HttpEntity<?> httpEntity = new HttpEntity<Object>(requestHeaders);

MyModel[] models ="/api/url", HttpMethod.GET, httpEntity, MyModel[].class);

But POSTs apparently don't work with
as it never sends the customized headers and I don't see how to set the request body using

What is the easiest way to make authenticated POST requests from RestTemplate?


Ok found the answer. exchange() is the best way. Oddly the HttpEntity class doesn't have a setBody() method (it has getBody()), but it is still possible to set the request body, via the constructor.

// Create the request body as a MultiValueMap
MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();     

body.add("field", "value");

// Note the body object as first parameter!
HttpEntity<?> httpEntity = new HttpEntity<Object>(body, requestHeaders);

MyModel model ="/api/url", HttpMethod.POST, httpEntity, MyModel.class);