在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中被删除了。
我想解决方法是将自己的另一个请求发送到重定向位置,但我希望有更好的解决方案。
答案 0 :(得分:0)
要使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);