user1757703
user1757703

Reputation: 3015

Java: Download file from URL when URL requests authentication

I am trying to download a file from a URL. The server runs apache httpd and requires username password login/authentication first. Then when I put this URL in a browser I get the download prompt to download this zip file.

How can I do this in Java? I am learning Java and I am from a Python background. Any help is greatly appreciated.

Edit: Server runs on HTTPS auth.

Upvotes: 1

Views: 5758

Answers (2)

Osmium USA
Osmium USA

Reputation: 1786

Or, if you want to be safe about it:

HttpResponse res;
DefaultHttpClient httpclient = new DefaultHttpClient();
String authorizationString = "Basic " + Base64.encodeToString(("admin" + ":" + "").getBytes(), Base64.NO_WRAP); //this line is diffe
authorizationString.replace("\n", "");
try {
    HttpGet request = new HttpGet(URI.create(url));
    request.addHeader("Authentication",authorizationString);
    res = httpclient.execute(request);
    return new MjpegInputStream(res.getEntity().getContent());              
} catch (ClientProtocolException e) {e.printStackTrace();}
} catch (IOException e) {e.printStackTrace();}

Upvotes: 1

AMADANON Inc.
AMADANON Inc.

Reputation: 5919

If the server uses BASIC authentication, you should be able to get the resource by specifying username/password in the URL: http://user:password@hostname/path/filename.ext

Browsers support this too, so you can try it in your browser quickly.

Upvotes: 0

Related Questions