使用java从互联网下载文件

使用java从互联网下载文件

本文介绍了使用java从互联网下载文件:如何认证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

感谢此线程类并注册。链接中的javadocs解释了如何。

You implement the Authenticator class and register it. The javadocs at the link explain how.

我不知道这是否与使用该问题的接受答案的nio方法配合使用,但它肯定适用于旧的方式是那个答案。

I don't know if this works with the nio method that got the accepted answer to the question, but it for sure works for the old fashioned way that was the answer under that one.

在认证器类实现中,你可能要使用一个并覆盖您的Authenticator实现的getPasswordAuthentication()方法以返回它。这将是通过您需要的用户名和密码的类。

Within the authenticator class implementation, you are probably going to use a PasswordAuthentication and override the getPasswordAuthentication() method of your Authenticator implementation to return it. That will be the class which is passed the user name and password you need.

根据您的请求,以下是一些示例代码:

Per your request, here is some sample code:

public static final String USERNAME_KEY = "username";
public static final String PASSWORD_KEY = "password";
private final PasswordAuthentication authentication;

public MyAuthenticator(Properties properties) {
    String userName = properties.getProperty(USERNAME_KEY);
    String password = properties.getProperty(PASSWORD_KEY);
    if (userName == null || password == null) {
        authentication = null;
    } else {
        authentication = new PasswordAuthentication(userName, password.toCharArray());
    }
}

protected PasswordAuthentication getPasswordAuthentication() {
    return authentication;
}

您在主要方法(或您之前的某个地方注册)调用URL):

And you register it in the main method (or somewhere along the line before you call the URL):

Authenticator.setDefault(new MyAuthenticator(properties));

使用情况很简单,但是我发现API对于您通常考虑的方式有所回旋,这些东西。非常典型的单身设计。

The usage is simple, but I find the API convoluted and kind of backwards for how you typically think about these things. Pretty typical of singleton design.

这篇关于使用java从互联网下载文件:如何认证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 05:32