我正在编写一个JUnit来测试使用Https和BasicAuthentication的Rest服务。以下是我的代码
@Test
public void testConnectionWithBasicAuthentication() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user", "password");
provider.setCredentials(AuthScope.ANY, credentials);
HttpResponse response;
try {
HttpClient client = createTrustAllHttpClientBuilder().setDefaultCredentialsProvider(provider).build();
response = client.execute( new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION));
int statusCode = response.getStatusLine().getStatusCode();
assertEquals(HttpStatus.SC_OK,statusCode);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static HttpClientBuilder createTrustAllHttpClientBuilder() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, (chain, authType) -> true);
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(builder.build(), NoopHostnameVerifier.INSTANCE);
return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory);
}
我总是得到401,服务器端显示我没有发送基本身份验证。
感谢任何帮助。