即使在请求工厂中将RestTemplate
设置为CloseableHttpClient
之后,与使用CloseableHttpClient
相比,使用httpClient
也会给我带来不同的响应。
使用CloseableHttpClient
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://localhost:8080/login/request.do");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", "abc@abc,com"));
params.add(new BasicNameValuePair("password", "abc123"));
params.add(new BasicNameValuePair("checkSum", "12343223ew42345rweawfdsfd"));
params.add(new BasicNameValuePair("action", "signin"));
params.add(new BasicNameValuePair("dojo.preventCache", "12342353425"));
httpPost.setEntity(new UrlEncodedFormEntity(params));
CloseableHttpResponse response = client.execute(httpPost);
if (200 == response.getStatusLine().getStatusCode()) {
String data = EntityUtils.toString(response.getEntity());
System.out.println(data);
ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(data);
JsonNode name = root.path("secureToken");
secureToken = name.asText();
}
client.close();
使用RestTemplate
final RestTemplate restTemplate = new RestTemplate();
final HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
final CloseableHttpClient httpClient = HttpClientBuilder.create().build();
factory.setHttpClient(httpClient);
restTemplate.setRequestFactory(factory);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("email", "abc@abc.com");
map.add("password", "abc123");
map.add("checkSum", "12343223ew42345rweawfdsfd");
map.add("action", "signin");
map.add("dojo.preventCache", "12342353425");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://localhost:8080/login/request.do", request, String.class);
if(responseEntity.getStatusCode().is2xxSuccessful())
{
ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(responseEntity.getBody());
JsonNode name = root.path("secureToken");
secureToken = name.asText();
}
使用CloseableHttpClient
时得到200的响应码,而使用RestTemplate
时得到302的响应码。
如果将RedirectStrategy
设置为LaxRedirectStrategy
,它将返回状态码200,但响应与从CloseableHttpClient
得到的响应不同。我得到的响应是从登录中呈现的最终UI的响应,这没有给我令牌。