java.net.HttpRetryException: cannot retry due to server authentication, in streaming mode
访问令牌获取代码:
private String getAccessToken() throws Exception {
String urlString = "/oauth/token";
HttpEntity<MultiValueMap<String, String>> request = getAccessTokenRequest();
ResponseEntity<JSONObject> responseEntity = restTemplate
.exchange(urlString, HttpMethod.POST, request, JSONObject.class);
assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
JSONObject userJson = responseEntity.getBody();
assertNotNull(userJson.get("access_token"));
assertEquals("bearer", userJson.get("token_type"));
return userJson.getString("access_token");
}
private HttpEntity<MultiValueMap<String, String>> getAccessTokenRequest() {
HttpHeaders headers = new HttpHeaders();
headers = setBasicAuthHeaders(headers);
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
MultiValueMap<String, String> requestMap = new LinkedMultiValueMap<>();
requestMap.add("grant_type", "client_credentials");
return new HttpEntity<>(requestMap, headers);
}
private HttpHeaders setBasicAuthHeaders(HttpHeaders headers) {
String authorization = "Basic " + new String(Base64Utils.encode("test:testsecret".getBytes()));
headers.add("Authorization", authorization);
return headers;
}
集成测试(getAccessToken()
函数调用中的始终错误):
@Test
public void createCustomer() throws Exception {
String accessToken = getAccessToken();
HttpHeaders headers = new HttpHeaders();
headers.add("Bearer", accessToken);
HttpEntity<String> entity = new HttpEntity<>(headers);
ResponseEntity<Customer> responseEntity = restTemplate
.exchange("/api/2.0/customers/save"+
"?firstName=" + customerToSave.getFirstName() +
"&lastName=" + customerToSave.getLastName(),
HttpMethod.GET, entity, Customer.class);
Customer customer = responseEntity.getBody();
assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
assertEquals(customerToSave.getLastName(), customer.getLastName());
}
测试类注释:
@ActiveProfiles("test")
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)