Apache HttpClient:BasicCredentialProvider无法使用SSL

时间:2018-04-25 22:25:50

标签: apache-httpclient-4.x

我正在编写一个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,服务器端显示我没有发送基本身份验证。

感谢任何帮助。

0 个答案:

没有答案