Link to home
Start Free TrialLog in
Avatar of Rene-Saim
Rene-SaimFlag for Türkiye

asked on

Login and download a file from a https web page within Java

Hi everyone,

I need a sample code loginning an htps web page and downloading a file there.

I searched a bit but yet I didn 't find a simple but complete one.
Avatar of Maen Abu-Tabanjeh
Maen Abu-Tabanjeh
Flag of Jordan image


This is the code from :
http://stackoverflow.com/questions/6439296/how-do-download-a-file-with-login-using-httpurlconnection
which should do it, which uses HttpClient
which you need to download from here:
http://apache.mirrorcatalogs.com//httpcomponents/httpclient/binary/httpcomponents-client-4.1.2-bin.zip


HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://example.com/login");
HttpResponse response = null;
List<NameValuePair> postFields = new ArrayList<NameValuePair>(2);

// Set the post fields
postFields.add(new BasicNameValuePair("username", "myusername"));
postFields.add(new BasicNameValuePair("password", "mypassword"));
post.setEntity(new UrlEncodedFormEntity(postFields, HTTP.UTF_8));

// Execute the POST request
response = client.execute(post);

// Now GET the file
HttpGet get = new HttpGet("http://example.com/files/myfile.mp3");
response = client.execute(get);

HttpEntity entity = response.getEntity();
InputStream in = entity.getContent();

// Save the file to SD
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
path.mkdirs();
File file = new File(path, "myfile.mp3");
FileOutputStream fos = new FileOutputStream(file);

byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
        fos.write(buffer, 0, len1);
}

fos.close();

Open in new window

Avatar of Rene-Saim

ASKER

Thank you very much for inspiring answers I found the way to accomplish the task by extending the Authenticator class.
ASKER CERTIFIED SOLUTION
Avatar of Rene-Saim
Rene-Saim
Flag of Türkiye image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
No actual solution has been committed since I first asked the question. So far I have searched the Java blogs and google and combined the working parts together which leaded having all-over solution.