尽管我在httpheaders中发送用户名和密码,但在使用RestTemplate实现时仍会收到org.springframework.web.client.HttpClientErrorException:401。我尝试调用的网址是“ https”
Here is my code :
method () {
HttpEntity<ReviewPayload> request = new HttpEntity<>(createHeaders(userName, password));
logger.info("HttpEntity Request: "+request);
ResponseEntity<MyPayload> response = restTemplate
.exchange("//https://abc7826:8443/api/matches", HttpMethod.POST, request, MyPayload.class);
HttpHeaders createHeaders(String username, String password){
return new HttpHeaders() {{
String auth = "Username" + ":" + "Password";
byte[] encodedAuth = Base64.encodeBase64(
auth.getBytes(Charset.forName("US-ASCII")) );
String authHeader = "Basic " + new String( encodedAuth );
set( "Authorization", authHeader );
}};
}
public RestTemplate restTemplate(){
TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
.loadTrustMaterial(null, acceptingTrustStrategy)
.build();
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(csf)
.build();
HttpComponentsClientHttpRequestFactory requestFactory =
new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
return new RestTemplate(requestFactory);
}