Apache HttpClient Digest authentication

前端 未结 4 1771
生来不讨喜
生来不讨喜 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:20

    You guys make it so complicated. If you read the documentation of apache httpclient, it would be super easy.

    protected static void downloadDigest(URL url, FileOutputStream fos)
        throws IOException {
        HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpClientContext context = HttpClientContext.create();
    
        String credential = url.getUserInfo();
        if (credential != null) {
            String user = credential.split(":")[0];
            String password = credential.split(":")[1];
    
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(user, password));
            AuthCache authCache = new BasicAuthCache();
            DigestScheme digestScheme = new DigestScheme();
            authCache.put(targetHost, digestScheme);
    
            context.setCredentialsProvider(credsProvider);
            context.setAuthCache(authCache);
        }
    
        HttpGet httpget = new HttpGet(url.getPath());
    
        CloseableHttpResponse response = httpClient.execute(targetHost, httpget, context);
    
        try {
            ReadableByteChannel rbc = Channels.newChannel(response.getEntity().getContent());
            fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        } finally {
            response.close();
        }
    }
    

提交回复
热议问题