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

use*_*413 15 java authentication download httpwebrequest basic-authentication

感谢这个线程如何使用Java从Internet下载和保存文件? 我知道如何下载文件,现在我的问题是我需要在我正在下载的服务器上进行身份验证.它是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)
Run Code Online (Sandbox Code Playgroud)

谢谢,

Yis*_*hai 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;
}
Run Code Online (Sandbox Code Playgroud)

然后在main方法中注册它(或在调用URL之前的某个位置):

Authenticator.setDefault(new MyAuthenticator(properties));
Run Code Online (Sandbox Code Playgroud)

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

  • 好吧,你只需要调用setDefault,那就是`Authenticator.setDefault(new Authenticator(){protected PasswordAuthentication getPasswordAuthentication(){return new PasswordAuthentication("login","pass".toCharArray());}});`I给我留下了深刻的印象 (3认同)

pou*_*def 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();
}
Run Code Online (Sandbox Code Playgroud)

上述代码存在问题:

  1. 这段代码不是生产就绪的(但它得到了重点.)

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

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

所以上面不是一个好的解决方案,但它确实有效,可以在以后轻松修改.


Kai*_*ran 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

写你的主要课程:

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
            }
        }

    }

}
Run Code Online (Sandbox Code Playgroud)