HttpClientErrorException: 401 Unauthorized basic a

2019-09-15 10:45发布

问题:

Im trying to get the url with basic authentication. I set the user/password as given below. The same credential is working in postman.

String RELATIVE_IDENTITY_URL  = "http://my_url/api/core/v3/people/email/abc@example.com";
    RestTemplate restTemplate;
    Credentials credentials;

    //1. Set credentials
    credentials = new UsernamePasswordCredentials("admin", "admin");

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials( AuthScope.ANY, credentials);

    //2. Bind credentialsProvider to httpClient
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
    CloseableHttpClient httpClient = httpClientBuilder.build();

    HttpComponentsClientHttpRequestFactory factory = new  
            HttpComponentsClientHttpRequestFactory(httpClient);

    //3. create restTemplate
    restTemplate = new RestTemplate();
    restTemplate.setRequestFactory(factory);

    //4. restTemplate execute
    String url = RELATIVE_IDENTITY_URL;

    String xml = restTemplate.getForObject(url,String.class); 
    System.out.println("Done");

I think the credentials are not set correctly. What is wrong here.? Error:

Exception in thread "main" org.springframework.web.client.HttpClientErrorException: 401 Unauthorized
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91)
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:667)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:620)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:580)
    at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:287)
    at com.src.AuthRestService.main(AuthRestService.java:85)    

回答1:

You are missing the auth header and setting the credentials in your rest template execution.