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.
Rene-SaimAsked:
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:
0
CEHJCommented:
0
for_yanCommented:

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

0
Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

Rene-SaimAuthor Commented:
Thank you very much for inspiring answers I found the way to accomplish the task by extending the Authenticator class.
0
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();
    try{
      if(!(p_url.charAt(p_url.length()-1)=='/')){
        p_url = new String(p_url + "/");
      }
      if(!(p_dest.charAt(p_dest.length()-1)=='/')){
        p_dest = new String(p_dest + "/");
      }
      //-->--You don t need to use this try block if you are not behind a proxy..
      try{
        // 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){
        System.err.println(e.toString());
      }
      //--<--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);
      try{
        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();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("GET");
        connection.setFollowRedirects(true);
      }
      catch (MalformedURLException e){
        System.out.println(e.toString());
      }
      catch (IOException e){
        System.out.println(e.toString());
      }
      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) + ")...");
      System.out.flush();
      FileOutputStream fos = null;
      if (l_download_file_name == null){
        return null;
      }
      else{
        fos = new FileOutputStream(p_dest + l_download_file_name);
      }

      int oneChar, count=0;

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

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.
0
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
Java

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.