Setting Security cookie using RestTemplate

前端 未结 3 1225
长情又很酷
长情又很酷 2021-01-04 21:48

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 achiev

相关标签:
3条回答
  • 2021-01-04 22:20

    I wrote a blog post that explains how to do this using request headers:

    http://springinpractice.com/2012/04/08/sending-cookies-with-resttemplate/

    Here's the code:

    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.add("Cookie", "JSESSIONID=" + session.getValue());
    HttpEntity requestEntity = new HttpEntity(null, requestHeaders);
    ResponseEntity rssResponse = restTemplate.exchange(
        "https://jira.example.com/sr/jira.issueviews:searchrequest-xml/18107/SearchRequest-18107.xml?tempMax=1000",
        HttpMethod.GET,
        requestEntity,
        Rss.class);
    Rss rss = rssResponse.getBody();
    
    0 讨论(0)
  • 2021-01-04 22:23

    This is how it has worked for us

    requestHeaders.add("Cookie", "JSESSIONID=" + session.getValue());
    
    0 讨论(0)
  • 2021-01-04 22:33

    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());
       }
    }
    
    0 讨论(0)
提交回复
热议问题