Download a file from the internet using java : How to authenticate?

后端 未结 6 1352
谎友^
谎友^ 2020-12-06 00:48

Thanks to this thread How to download and save a file from Internet using Java? I know how to download a file, now my problem is that I need to authenticate on the sever fro

6条回答
  •  执念已碎
    2020-12-06 01:27

    This is some code I wrote that fetches a website and displays the contents to System.out. It uses Basic authentication:

    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();
    }
    

    Problems with the above code:

    1. This code isn't production-ready (but it gets the point across.)

    2. The code yields this compiler warning:

    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
    

    One really should use the Authenticator class, but for the life of me, I could not figure out how and I couldn't find any examples either, which just goes to show that the Java people don't actually like it when you use their language to do cool things. :-P

    So the above isn't a good solution, but it does work and could easily be modified later.

提交回复
热议问题