Spring RestTemplate重定向302 [英] Spring RestTemplate redirect 302
问题描述
我正在尝试使用spring rest模板进行发布请求以登录.
I'm trying to use spring rest template to do a post request to login in.
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,我想按照此请求获取正文响应,因为我没有获得该请求的正文.
My ResponseEntity status is 302, i want to follow this request to get the body response , because i didn't get the body for this request.
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 -
我该怎么做才能解决这个问题?!
What can I do to solve this problem ?!
推荐答案
如果请求是GET请求,则会自动遵循重定向(请参阅 LaxRedirectStrategy ):
The redirection is followed automatically if the request is a GET request (see this answer). To make it happen on POST requests, one option might be to use a different request factory, like HttpComponentsClientHttpRequestFactory
, and set it to use an HttpClient
with the required settings to follow the redirect (see 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);
我还没有测试过,但这应该可以工作.
I haven't tested, but this should work.
这篇关于Spring RestTemplate重定向302的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!