I am trying to call a Restful JSON service using RestTemplate and Jackson json convertor. Now in order to call the service I need to pass in a Security cookie. I can achieve this by using URLConnection (See the code below)
URL url= new URL("https://XXXXXXXX");
URLConnection yc = url.openConnection();
yc.setRequestProperty("SecurityCookie", ssocookie.getValue());
Whats the parallel for this in RestTemplate? Here is a code snippet which I have been using to call a Restful Service using RestTemplate:
RestTemplate rest = new RestTemplate();
InputBean input = new InputBean();
input.setResource("SampleResource");
HttpEntity<InputBean> entity = new HttpEntity<InputBean>(input);
ResponseEntity<OutputBean> response1 = rest.postForEntity(
"https://XXXXXXXXX",
entity, OutputBean.class);
I can not figure out how to pass the security cookie while using RestTemplate to call the service. Any help on this would be great.
You can access the underlying HttpURLConnection
used by RestTemplate
by wiring your RestTemplate
up with a custom ClientHttpRequestFactory
, which lets you access the underlying connection to set headers, properties, etc. The ClientHttpRequestFactory
is used by RestTemplate
when creating new connections.
In particular, you can extend the SimpleClientHttpRequestFactory
implementation and override the prepareConnection()
method:
public class YourClientHttpRequestFactory extends SimpleClientHttpRequestFactory {
@Override
protected void prepareConnection(HttpURLConnection connection, String httpMethod) {
connection.setRequestProperty("SecurityCookie", ssocookie.getValue());
}
}