使用java从Internet下载文件:如何进行身份验证?

时间:2009-06-05 12:40:47

标签: java authentication httpwebrequest download basic-authentication

感谢这个帖子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)

谢谢,

6 个答案:

答案 0 :(得分:15)

扩展Authenticator类并注册它。链接中的javadoc解释了如何。

我不知道这是否适用于获得该问题的已接受答案的nio方法,但它肯定适用于那种老式的方式,而不是那个方法。

在authenticator类实现中,您可能会使用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;
}

你在main方法中注册它(或在你调用URL之前的某个地方):

Authenticator.setDefault(new MyAuthenticator(properties));

用法很简单,但我发现API很复杂,而且对于你通常如何思考这些事情有点倒退。非常典型的单身设计。

答案 1 :(得分:7)

这是我编写的一些代码,用于获取网站并将内容显示给System.out。它使用基本身份验证:

import java.net.*;
import java.io.*;

public class foo {
    public static void main(String[] args) throws Exception {

   URL yahoo = new URL("http://www.MY_URL.com");

   String passwdstring = "USERNAME:PASSWORD";
   String encoding = new 
          sun.misc.BASE64Encoder().encode(passwdstring.getBytes());

   URLConnection uc = yahoo.openConnection();
   uc.setRequestProperty("Authorization", "Basic " + encoding);

   InputStream content = (InputStream)uc.getInputStream();
   BufferedReader in   =   
            new BufferedReader (new InputStreamReader (content));

   String line;
   while ((line = in.readLine()) != null) {
      System.out.println (line);
   }   

   in.close();
}

上述代码存在问题:

  1. 此代码不适合生产(但它可以解决问题。)

  2. 代码会产生此编译器警告:

  3. foo.java:11: warning: sun.misc.BASE64Encoder is Sun proprietary API and may be removed in a future release
          sun.misc.BASE64Encoder().encode(passwdstring.getBytes());
                  ^ 1 warning
    

    一个人真的应该使用Authenticator类,但是对于我的生活,我无法弄清楚我怎么也找不到任何例子,这只是为了表明Java人员实际上并不喜欢它你用他们的语言来做很酷的事情。 :-P

    所以上面的内容不是好的解决方案,但它确实有效,以后可以轻松修改。

答案 2 :(得分:6)

为Authenticator编写重写类:

import java.net.Authenticator;
import java.net.PasswordAuthentication;

public class MyAuthenticator extends Authenticator {  
    private static String username = "";
    private static String password = "";

    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication (MyAuthenticator.username, 
                MyAuthenticator.password.toCharArray());
    }

    public static void setPasswordAuthentication(String username, String password) {
        MyAuthenticator.username = username;
        MyAuthenticator.password = password;
    }
}

写下你的主要课程:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.MalformedURLException;
import java.net.URL;

public class MyMain{


    public static void main(String[] args) {
        URL url;
        InputStream is = null;
        BufferedReader br;
        String line;

        // Install Authenticator
        MyAuthenticator.setPasswordAuthentication("Username", "Password");
        Authenticator.setDefault (new MyAuthenticator ());

        try {
            url = new URL("Your_URL_Here");
            is = url.openStream();  // throws an IOException
            br = new BufferedReader(new InputStreamReader(is));
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (MalformedURLException mue) {
             mue.printStackTrace();
        } catch (IOException ioe) {
             ioe.printStackTrace();
        } finally {
            try {
                if (is != null) is.close();
            } catch (IOException ioe) {
                // nothing to see here
            }
        }

    }

}

答案 3 :(得分:1)

您是否尝试使用http://user:password@domain/path

格式构建网址?

答案 4 :(得分:1)

我建议从apache http://hc.apache.org/httpclient-3.x/查看HttpClient,这样可以非常轻松地下载/验证

答案 5 :(得分:0)

这个开源库http://spnego.sourceforge.net也有一些关于如何使用它的SpnegoHttpURLConnection类的例子。

该类中的一个构造函数允许您传入用户名和密码。

查看类的java doc以获取示例。

相关问题