13

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 を認識しません。

4

2 に答える 2

24

デフォルトの 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;
    }
}
于 2012-10-11T13:03:47.993 に答える
9

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;
  }

}

于 2013-10-09T23:45:07.620 に答える