KMH
KMH

Reputation: 95

Connect to remote server with username/password for downloading files

I need to connect to a remote server which requires username/password and need to download videos and other pdf documents. What is the best way in java. A little code sample will be highly appreciable. I tried following, accept my apologies in advance if this code seems like a novice effort as I just started Java and learning the best practices from the guru's like you :). Problem is how to authenticate, how to provide username/password to the server.

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;


public class Downloader {
URL url;
public Downloader(){
    try {
        url = new URL("https://d396qusza40orc.cloudfront.net/algs4partI/slides%2F13StacksAndQueues.pdf");
        try {
            URLConnection con = url.openConnection();
            con.connect();
            InputStream inStream = url.openStream();
            FileOutputStream outStream = new FileOutputStream("data.dat");
            int bytesRead;
            byte[] buffer = new byte[100000];
            while((bytesRead = inStream.read(buffer)) > 0){

                outStream.write(buffer, 0 , bytesRead);
                buffer = new byte[100000];
            }
            outStream.close();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
public static void main(String[] args){
    Downloader d = new Downloader();
}
}

Upvotes: 0

Views: 6167

Answers (1)

Kris
Kris

Reputation: 14458

You should be able to provide the username/password as part of the URL:

E.g.

https://username:[email protected]/secure/myfile.pdf

This does assume that the site is using standard HTTP authentication.

If some sort of custom authentication is being done you may need to supply a per-generated cookie containing authentication information or possibly do a separate log-in request before trying to download your file. This will all depend on the setup of the remote server.

Upvotes: 1

Related Questions