Java 异常:未授权:401

Java Exception: Unauthorized: 401

我收到错误:Exception: org.springframework.web.client.HttpClientErrorException$Unauthorized: 401,当我尝试通过 HttpHeader 连接到 Jira 时,凭据是在配置服务器文件中配置的,即:

@Component
public class JiraHttpHeadersHelper {

    @Value("${first.jira.auth.user}")
    private String firstJiraAuthUser;

    @Value("${first.jira.auth.psw}")
    private String firstJiraAuthPsw;


    public HttpHeaders jiraHeadersWithAuthentication() {
        String plainCreds = firstJiraAuthUser + ":" + firstJiraAuthPsw;

        System.out.println("Credenciales JiraServices: "+plainCreds);
        byte[] base64CredsBytes = Base64.getEncoder().encode(plainCreds.getBytes());
        String base64Creds = new String(base64CredsBytes);

        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Basic" + base64Creds);
        headers.setContentType(MediaType.APPLICATION_JSON);

        System.out.println("Authorization JiraServices: "+headers);
        return headers;
    }
}

我命令调用上面的文件以及在行 ResponseEntity<String> result = restTemplate.exchange(url, HttpMethod.GET,this.requestEnt, String.class); 上出现错误的方法是这样的:

    public ResponseEntity<String> getPriorityJira() {

        //Request entity created
        this.requestEnt = new HttpEntity(this.jiraHttpHeadersHelper.jiraHeadersWithAuthentication());

        String jql = "priority";
        String url = jiraBaseURL + jql;
        try {
            ResponseEntity<String> result = restTemplate.exchange(url, HttpMethod.GET,this.requestEnt, String.class);
            System.out.println("HttpStatus"+HttpStatus.OK);
            if (result.getStatusCode() == HttpStatus.OK) {
                return result;
            } else {
                logger.error("Jira Generic User maybe blocked, status from API: " +result.getStatusCode() + ". Body: "+ result.getBody());
                return new ResponseEntity<>(result.getBody(), result.getStatusCode());
            }
        } catch(HttpClientErrorException e) {
            logger.error("Error getting priorityJira. Exception: "+ e);
            return new ResponseEntity<>(e.getStatusCode());
        }
    }

事实上,当我 运行 调试并检查凭据时,它会毫无问题地显示出来。我已经搜索过,尝试过此页面上的大部分链接,但找不到解决方案。 在这种情况下,我们将不胜感激,在此先感谢。

当您定义您的授权时 header 您将您的密钥与 « Basic » 连接起来而不添加白色 space。

headers.add("Authorization", "Basic" + base64Creds);

而不是:

headers.add("Authorization", "Basic " + base64Creds);

也许就是这样。

编辑: 答案是将 StandardCharsets.UTF-8 添加到 String 构造函数。