微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用java从互联网下载文件:如何认证?

感谢这个线程 How to download and save a file from Internet using Java?
我知道如何下载文件,现在我的问题是我需要在我正在下载的服务器上进行身份验证.这是一个到subversion服务器的http接口.我需要查找哪个领域?

使用最后一个注释中发布的代码,我得到这个异常:

java.io.IOException: Server returned HTTP response code: 401 for URL: http://myserver/systemc-2.0.1.tgz
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1305)
    at java.net.URL.openStream(URL.java:1009)
    at mypackage.Installer.installSystemc201(Installer.java:29)
    at mypackage.Installer.main(Installer.java:38)

谢谢,

解决方法

您实现了 Authenticator类并注册.链接中的javadocs解释了如何.

我不知道这是否与nio方法一致,得到了对该问题的接受的答案,但它确实适用于那种那种老式的方式.

在认证器类实现中,您可能要使用PasswordAuthentication并覆盖您的Authenticator实现的getpasswordAuthentication()方法来返回它.这将是通过您需要的用户名和密码的类.

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

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之前沿线的某个地方)注册它:

Authenticator.setDefault(new MyAuthenticator(properties));

用法很简单,但是我发现API对于你通常如何思考这些东西而言是一个倒塌的方式.非常典型的单身设计.

原文地址:https://www.jb51.cc/java/122740.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐