【问题标题】:Android RestTemplate j_spring_security_check not redirectingAndroid RestTemplate j_spring_security_check 不重定向
【发布时间】:2015-09-30 08:43:45
【问题描述】:

在我正在开发的 Android 应用程序中,我正在使用 RestTemplate 发布登录请求(Spring Security):

RestTemplate restTemplate = new RestTemplate();

HttpHeaders headers = new HttpHeaders();
headers.add("j_username", uname);
headers.add("j_password", password);
headers.add("submit", "Login");
HttpEntity<String> entity = new HttpEntity<String>(null, headers);
ResponseEntity<String> reply = restTemplate.exchange(baseUrl + "/j_spring_security_check", HttpMethod.POST, entity, String.class);

回复:

<302 Found,{Date=[Wed, 30 Sep 2015 08:10:15 GMT], Server=[Apache-Coyote/1.1], Location=[http://192.168.100.81/rest/loginstatus;jsessionid=A63589BF9985296C42A8FC49C858F2AA], Content-Length=[0], Set-Cookie=[JSESSIONID=A63589BF9985296C42A8FC49C858F2AA; Path=/], Keep-Alive=[timeout=5, max=100], Connection=[Keep-Alive], X-Android-Sent-Millis=[1443600616746], X-Android-Received-Millis=[1443600616756]}>

如您所见,它应该重定向到位置,但事实并非如此。我了解默认行为是仅在 GET 请求上重定向。

我怎样才能使这个请求跟随重定向?我见过很多使用 Apache 的 HttpClient 的解决方案,它在 API 23 中被移除。

我想一种解决方法是自己向重定向位置发布另一个请求,但我希望有更好的解决方案。

【问题讨论】:

  • j_spring_security_check 用于表单提交,不推荐用于 REST。

标签: android spring-security resttemplate


【解决方案1】:

RestTemplate 始终遵循重定向:

RestTemplate restTemplate = new RestTemplate(new SimpleClientHttpRequestFactory() {
    @Override
    protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException
    {
        super.prepareConnection(connection, httpMethod);
        connection.setInstanceFollowRedirects(true);
    }
});

更新:您构造的HttpEntity 错误,j_username 等不是标题。你可能想要:

MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
form.add("j_username", uname);
form.add("j_password", password);
HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(form, null);

【讨论】:

  • 这会导致错误代码 400 错误请求。响应也需要很长时间才能到达。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-26
  • 2015-04-20
  • 2015-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多