RestTemplate和Cookie

时间:2012-04-16 14:03:30

标签: spring resttemplate

我需要发送一个HTTP cookie,我正在使用RestTemplate

HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.add("Cookie", "SERVERID=c52");
HttpEntity requestEntity = new HttpEntity(null, requestHeaders);
ResponseEntity responses = restTemplate.exchange(webService.getValidateUserUrl(),
       HttpMethod.POST, requestEntity,  String.class, mapValidateUser);

但是,接收服务器看不到cookie。

2 个答案:

答案 0 :(得分:21)

默认的rest模板不使用持久连接,这是我使用的。

public class StatefullRestTemplate extends RestTemplate
{
    private final HttpClient httpClient;
    private final CookieStore cookieStore;
    private final HttpContext httpContext;
    private final StatefullHttpComponentsClientHttpRequestFactory statefullHttpComponentsClientHttpRequestFactory;

    public StatefullRestTemplate()
    {
        super();
        HttpParams params = new BasicHttpParams();
        HttpClientParams.setRedirecting(params, false);

        httpClient = new DefaultHttpClient(params);
        cookieStore = new BasicCookieStore();
        httpContext = new BasicHttpContext();
        httpContext.setAttribute(ClientContext.COOKIE_STORE, getCookieStore());
        statefullHttpComponentsClientHttpRequestFactory = new StatefullHttpComponentsClientHttpRequestFactory(httpClient, httpContext);
        super.setRequestFactory(statefullHttpComponentsClientHttpRequestFactory);
    }

    public HttpClient getHttpClient()
    {
        return httpClient;
    }

    public CookieStore getCookieStore()
    {
        return cookieStore;
    }

    public HttpContext getHttpContext()
    {
        return httpContext;
    }

    public StatefullHttpComponentsClientHttpRequestFactory getStatefulHttpClientRequestFactory()
    {
        return statefullHttpComponentsClientHttpRequestFactory;
    }

}


public class StatefullHttpComponentsClientHttpRequestFactory extends HttpComponentsClientHttpRequestFactory
{
    private final HttpContext httpContext;

    public StatefullHttpComponentsClientHttpRequestFactory(HttpClient httpClient, HttpContext httpContext)
    {
        super(httpClient);
        this.httpContext = httpContext;
    }

    @Override
    protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri)
    {
        return this.httpContext;
    }
}

答案 1 :(得分:6)

您还可以扩展RestTemplate:

public class CookieRestTemplate extends RestTemplate {

  @Override
  protected ClientHttpRequest createRequest(URI url, HttpMethod method) throws IOException {
    ClientHttpRequest request = super.createRequest(url, method);

    request.getHeaders().add("Cookie", "SERVERID=c52");
    return request;
  }

}