I want to set the value of the Accept:
in a request I am making using Spring's RestTemplate
.
Here is my Spring request handling code
@RequestMapping(
value= "/uom_matrix_save_or_edit",
method = RequestMethod.POST,
produces="application/json"
)
public @ResponseBody ModelMap uomMatrixSaveOrEdit(
ModelMap model,
@RequestParam("parentId") String parentId
){
model.addAttribute("attributeValues",parentId);
return model;
}
and here is my Java REST client:
public void post(){
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
params.add("parentId", "parentId");
String result = rest.postForObject( url, params, String.class) ;
System.out.println(result);
}
This works for me; I get a JSON string from the server side.
My question is: how can I specify the Accept:
header (e.g. application/json
,application/xml
, ... ) and request method (e.g. GET
,POST
, ... ) when I use RestTemplate?
If, like me, you struggled to find an example that uses headers with basic authentication and the rest template exchange API, this is what I finally worked out...
Code : calling rest api using template
1)
or
2)
Method creating json object
You could set an interceptor "ClientHttpRequestInterceptor" in your RestTemplate to avoid setting the header every time you send a request.
Then
Here is a simple answer. Hope it helps someone.
I suggest using one of the
exchange
methods that accepts anHttpEntity
for which you can also set theHttpHeaders
. (You can also specify the HTTP method you want to use.)For example,
I prefer this solution because it's strongly typed, ie.
exchange
expects anHttpEntity
.However, you can also pass that
HttpEntity
as arequest
argument topostForObject
.This is mentioned in the
RestTemplate#postForObject
Javadoc.