Basically what I need to do is to perform digest authentication. First thing I tried is the official example available here. But when I try to execute it(with some small ch
private static byte[] downloadFileWithDigitAuth(String url, String username, String password) {
byte[] bytes = null;
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet(url);
HttpContext httpContext = new BasicHttpContext();
CloseableHttpResponse httpResponse = null;
try {
httpResponse = httpClient.execute(httpGet, httpContext);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
Header authHeader = httpResponse.getFirstHeader(AUTH.WWW_AUTH);
DigestScheme digestScheme = new DigestScheme();
/*
override values if need
No need override values such as nonce, opaque, they are generated by server side
*/
digestScheme.overrideParamter("realm", "User Login Required !!");
digestScheme.processChallenge(authHeader);
UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
httpGet.addHeader(digestScheme.authenticate(creds, httpGet, httpContext));
httpResponse.close();
httpResponse = httpClient.execute(httpGet);
}
bytes = IOUtils.toByteArray(httpResponse.getEntity().getContent());
} catch (IOException | MalformedChallengeException | AuthenticationException e) {
e.printStackTrace();
}
finally {
if (httpResponse != null) {
try {
httpResponse.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return bytes;
}
Gradle :
compile group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.12'
compile group: 'commons-io', name: 'commons-io', version: '2.6'