surya
surya

Reputation: 2749

download file from url with authentication

i have a secured url , if i open in browser, a pop up comes and i authenitcate with userid/password, then a pdf file is downloaded .

I want this functionality in java. It should authenticate using proxy server/port and user details then download

URL server = new URL("http://some.site.url/download.aspx?client=xyz&docid=1001");
System.setProperty("https.proxyUser", userName);
System.setProperty("https.proxyPassword", password);

System.setProperty("https.proxyHost",proxy);
System.setProperty("https.proxyPort",port);

URLConnection connection = (URLConnection)server.openConnection();
connection.connect();
InputStream is = connection.getInputStream();

//then i read this input stream and write to a pdf file in temporary folder

It gives me connection timeout error.

Then i thought adding authentication

String authentication = "Basic " + new
sun.misc.BASE64Encoder().encode("myuserid:mypassword".getBytes());
connection.setRequestProperty("Proxy-Authorization", authentication);

Still doesnt work,

Please let me know .

Upvotes: 4

Views: 15664

Answers (1)

surya
surya

Reputation: 2749

I solved this issue. I used a customized authenticator before connecting the URL, and it authenticates and downloads the document. FYI - once connected, till next server restart, it doesn't need authentication.

URL server = new URL(url); //works for https and not for http, i needed https in  my case.
Authenticator.setDefault((new MyAuthenticator()));

URLConnection connection = (URLConnection)server.openConnection();
connection.connect();
InputStream is = connection.getInputStream();
.... //write code to fetch inputstream

Define your own authenticator as given below

public class MyAuthenticator extends Authenticator {
    final PasswordAuthentication authentication;

    public MyAuthenticator(String userName, String password) {
         authentication = new PasswordAuthentication(userName, password.toCharArray());
    }
}

Upvotes: 0

Related Questions