Apache HttpClient Digest authentication

前端 未结 4 1778
生来不讨喜
生来不讨喜 2020-11-28 13:28

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

4条回答
  •  佛祖请我去吃肉
    2020-11-28 14:15

    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'
    

提交回复
热议问题