【问题标题】:Spring RestTemplate redirect 302Spring RestTemplate 重定向 302
【发布时间】:2015-11-30 07:00:41
【问题描述】:

我正在尝试使用 spring rest 模板发出登录请求。

RestTemplate restTemplate = new RestTemplate();

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

LinkedMultiValueMap<String, Object> mvm = new LinkedMultiValueMap<String, Object>();
mvm.add("LoginForm_Login", "login");
mvm.add("LoginForm_Password", "password");

ResponseEntity<String> result = restTemplate.exchange(uriDWLogin, HttpMethod.POST, requestEntity, String.class);

我的 ResponseEntity 状态是 302,我想按照这个请求来获取正文响应,因为我没有得到这个请求的正文。

18:59:59.170 MAIN [http-nio-8080-exec-83] DEBUG c.d.s.c.DemandwareCtlr - loginToSandbox - StatusResponse - 302
18:59:59.170 MAIN [http-nio-8080-exec-83] DEBUG c.d.s.c.DemandwareCtlr - loginToSandbox - BodyResponse - 

我能做些什么来解决这个问题?!

【问题讨论】:

    标签: spring rest redirect response http-status-code-302


    【解决方案1】:

    如果请求是 GET 请求,则会自动遵循重定向(请参阅this answer)。要使其在 POST 请求中发生,一种选择可能是使用不同的请求工厂,例如 HttpComponentsClientHttpRequestFactory,并将其设置为使用 HttpClient 并具有遵循重定向所需的设置(请参阅 LaxRedirectStrategy):

    final RestTemplate restTemplate = new RestTemplate();
    final HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
    final HttpClient httpClient = HttpClientBuilder.create()
                                                   .setRedirectStrategy(new LaxRedirectStrategy())
                                                   .build();
    factory.setHttpClient(httpClient);
    restTemplate.setRequestFactory(factory);
    

    我还没有测试过,但这应该可以。

    【讨论】:

    • 感谢您的帮助,它有效,现在我需要获取“Cookie”而不是“Set-cookie”,我该怎么做?
    • 只需从标题中获取“Set-Cookie”,就像使用 cookie 一样,result.getHeaders().get("Set-Cookie").get(0).split(" ;")[0];
    • 如果 org.apache.httpcomponents:httpclient 在类路径上,RestTemplate 的行为是不同的——它不遵循 GET 上的重定向(使用默认构造函数)。
    • SimpleClientHttpRequestFactory 不遵循重定向它遵循重定向。只有一个。
    猜你喜欢
    • 2015-06-07
    • 2020-08-28
    • 2018-05-19
    • 2016-08-29
    • 2017-09-20
    • 1970-01-01
    • 2011-09-25
    • 2014-11-10
    • 2019-04-12
    相关资源
    最近更新 更多