簡體   English   中英

為什么即使憑據正確,我也會收到 401 unauthorized?

[英]Why do i get 401 unauthorised even though credentials are correct?

我正在嘗試在具有基本身份驗證的 API 上發出獲取請求,但即使我有正確的用戶名和密碼,它也不起作用。

當我嘗試使用 curl(Linux 命令)訪問 API 時,它工作正常。

curl -u "user:password" -s https://dummy/link/1

我是否需要指定響應必須在enter code here JSON?

我正在使用 Maven: org.apache.httpcomponents:httpclient:4.5.13 依賴

CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user","password");
provider.setCredentials(AuthScope.ANY, credentials);

HttpClient client = HttpClientBuilder.create()
    .setDefaultCredentialsProvider(provider)
    .build();

HttpResponse response = client.execute(
    new HttpGet("https://dummy/link/1");
int statusCode = response.getStatusLine()
    .getStatusCode();

if(statusCode != HttpStatus.SC_OK){
  System.out.println(statusCode);
}else{
  System.out.println(response);
}

我偶然發現了同樣的問題。 我注意到我對 curl 的請求有 header

Authorization: Basic base64(username:password)

我的獲取請求丟失了,然后我找到了解決問題的答案,但不推薦使用BasicScheme.authenticate並最終使用另一個答案刪除了不推薦使用的部分:

httpget.setHeader( new BasicScheme(StandardCharsets.UTF_8).authenticate(credentials , httpget, null) );

現在可以了。 沒有檢查第一個答案中指定的長途。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM