我正在尝试在android中实现 Digest auth 。我阅读了很多帖子,他们说 HttpUrlConnection 类不支持Digest身份验证。但是,我已使用bare-bones-digest库实现了它。现在它工作正常,但API调用变得非常慢。与使用基本身份验证相比,加载数据需要两倍的时间。他们说使用base-bones-digest避免每次发送两次请求,在后续请求中客户端可以重用挑战。只有第一个请求必须发送两次。但没有给出实施。
HttpURLConnection httpURLConnection = null;
try {
if(mAuthorizationString != null && !mAuthorizationString.equals("")){
URL url = new URL(apiEndpoint);
httpURLConnection = (HttpURLConnection) url.openConnection();
DigestAuthentication auth = DigestAuthentication.fromResponse(httpURLConnection);
// ...with correct credentials
auth.username("username").password("password");
httpURLConnection.setRequestProperty(DigestChallengeResponse.HTTP_HEADER_AUTHORIZATION,
mAuthorizationString);
}
else{
URL url = new URL(apiEndpoint);
httpURLConnection = (HttpURLConnection) url.openConnection();
// Step 2. Make the request and check to see if the response contains an authorization challenge
if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
// Step 3. Create an authentication object from the challenge...
DigestAuthentication auth = DigestAuthentication.fromResponse(httpURLConnection);
// ...with correct credentials
auth.username("username").password("password");
// Step 4 (Optional). Check if the challenge was a digest challenge of a supported type
if (!auth.canRespond()) {
// No digest challenge or a challenge of an unsupported type - do something else or fail
return httpURLConnection;
}
// Step 5. Create a new connection, identical to the original one...
httpURLConnection = (HttpURLConnection) url.openConnection();
mAuthorizationString = auth.getAuthorizationForRequest(requestMethod, httpURLConnection.getURL().getPath());
// ...and set the Authorization header on the request, with the challenge response
httpURLConnection.addRequestProperty(DigestChallengeResponse.HTTP_HEADER_AUTHORIZATION,
mAuthorizationString);
}
}
} catch (IOException e) {
e.printStackTrace();
}
答案 0 :(得分:0)
我已经通过更新代码修复了我自己。
@Deprecated
public void someDeprecatedFunction() {