java HttpClientErrorException: 401 未经授权的基本身份验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44285338/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 08:03:37  来源:igfitidea点击:

HttpClientErrorException: 401 Unauthorized basic authentication

javaspringbasic-authentication

提问by being_uncertain

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

我试图通过基本身份验证获取 url。我设置了用户/密码,如下所示。同样的凭证在邮递员中工作。

String RELATIVE_IDENTITY_URL  = "http://my_url/api/core/v3/people/email/[email protected]";
    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)    

回答by Mike Tung

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

您缺少 auth 标头并在您的其余模板执行中设置凭据。