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.
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Maen Abu-TabanjehNetwork Administrator, Network ConsultantCommented:

This is the code from :
which should do it, which uses HttpClient
which you need to download from here:

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


Open in new window

Become a CompTIA Certified Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

Rene-SaimAuthor Commented:
Thank you very much for inspiring answers I found the way to accomplish the task by extending the Authenticator class.
Rene-SaimAuthor Commented:
import java.lang.*;
import java.net.*;

public class MyAuthenticator extends Authenticator {
    // This method is called when a password-protected URL is accessed
    protected PasswordAuthentication getPasswordAuthentication() {
        // Get information about the request
        String promptString = getRequestingPrompt();
        String hostname = getRequestingHost();
        InetAddress ipaddr = getRequestingSite();
        int port = getRequestingPort();

        // Get the username from the user...
        String username = "<here comes the user name>";

        // Get the password from the user...
        String password = "<here comes the password>";

        // Return the information
        return new PasswordAuthentication(username, password.toCharArray());

  public static String fileDownload(String p_url, String p_file_type, String p_date_str, String p_dest){
    String l_download_file_name = new String();
        p_url = new String(p_url + "/");
        p_dest = new String(p_dest + "/");
      //-->--You don t need to use this try block if you are not behind a proxy..
        // Modify system properties
        java.util.Properties sysProperties = System.getProperties();
        // Specify proxy settings
        sysProperties.put("proxySet",  "true");
        sysProperties.put("proxyHost", "<here comes the proxy host>");
        sysProperties.put("proxyPort", "<here comes the proxy port>");
      catch(Exception e){
      //--<--You don t need to use this try block if you are not behind a proxy..
      // Install the custom authenticator
      Authenticator.setDefault(new MyAuthenticator());
      l_download_file_name = "<here comes the file name to  download>"
      HttpsURLConnection connection = null;
      URL url = new URL(p_url + l_download_file_name);
        System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
        java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        connection = (HttpsURLConnection) url.openConnection();
      catch (MalformedURLException e){
      catch (IOException e){
      InputStream is = url.openStream();
      System.out.print("Copying resource (type: " + connection.getContentType());
      Date date=new Date(connection.getLastModified());
      System.out.println(", modified on: " + DateFormat.getDateInstance().format(date) + ")...");
      FileOutputStream fos = null;
      if (l_download_file_name == null){
        return null;
        fos = new FileOutputStream(p_dest + l_download_file_name);

      int oneChar, count=0;

      while ((oneChar=is.read()) != -1){
      System.out.println(count + " byte(s) copied");
    catch (MalformedURLException e){
    catch (IOException e){
    return l_download_file_name;

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Rene-SaimAuthor Commented:
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.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.