Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

How do I connect to an https URL to download a file?

Posted on 2008-11-06
12
Medium Priority
?
743 Views
Last Modified: 2012-06-27
I am writing a java program to download a daily file from an https url.
i.e. https://example.net/Downloads/guid.zip

I have a truststore and keystore configured correctly.
I have also been given a username and password.

My problem at this point is with the connection.  When I attempt to connect, I get the following error:
Access denied (java.util.PropertyPermission javax.net.ssl.keyStore write)

I'm not exactly sure where to incorporate my username and password. Also, not sure what the setRequestProperty to look like.   My code is below.

System.setProperty( "javax.net.ssl.keyStore", "/is/domains/domain48000/config/clientkeystore.jks" );
            System.setProperty( "javax.net.ssl.keyStorePassword", "kspass" );
            System.setProperty( "javax.net.ssl.trustStore", "/is/domains/domain48000/config/cacerts.jks" );
            System.setProperty( "javax.net.ssl.trustStorePassword", "tspass" );
            java.net.URL url = new java.net.URL( https://example.net/Downloads/guid.zip );
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setDoInput( true );
            conn.setDoOutput( true );
            conn.setUseCaches( false );
            conn.setRequestProperty( "Content-Type", "text/xml" );
            InputStream stream = conn.getInputStream();
            BufferedInputStream in = new BufferedInputStream( stream );
            FileOutputStream file = new FileOutputStream( "/home/myFile.zip" );
            BufferedOutputStream out = new BufferedOutputStream( file );
            int i;
            while ((i = in.read()) != -1) {
                out.write( i );
            }
            out.flush();

Open in new window

0
Comment
Question by:cindymccartney
12 Comments
 
LVL 16

Expert Comment

by:Bryan Butler
ID: 22902359
So is the error happening on line 2 then?
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 2000 total points
ID: 22903080
You're complicating the issue: there should be no need to manipulate SSL properties. All you need to do is authenticate:

http://www.exampledepot.com/egs/java.net/Auth.html

and copy the stream:


IOUtils.copyStream(conn.getInputStream(), new FileOutputStream( "/home/myFile.zip" ));
 
// At http://www.technojeeves.com/joomla/index.php/free/51-copying-streams

Open in new window

0
 
LVL 13

Expert Comment

by:marchent
ID: 22906107
Firstly install Openssl to support HTTPS communication. Download OpenSSL exe from web and install, then can use below code.
import java.io.*;
import java.net.*;
 
class Test{
    
    public void getZip(String link, String file) throws Exception{
        URL url = new URL(link);
        URLConnection urlConnection = url.openConnection();
        DataInputStream dis = new DataInputStream(urlConnection.getInputStream());
        DataOutputStream out = new DataOutputStream(new FileOutputStream( file  ) );
        
        int i;
        while ((i = dis.read()) != -1) {
            out.write( i );
        }
        out.flush();
        dis.close();
    }
    
    public static void main(String []argv) throws Exception{
        new Test().getZip("https://code.bandit-project.org/trac/export/3/trunk/RoleEngine/doc/rejavadoc.zip", "out.zip");
    }
}

Open in new window

0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:cindymccartney
ID: 22906888
CEHJ -

I attempted to your solution, but am having a problem.  I created a new package to hold the MyAuthenticator class and imported that package into my main java program.  

The first line in my code (as per the example) is this:

java.net.Authenticator.setDefault( new com.dva.Authenticator.MyAuthenticator() );

However, I am getting a "class com.dva.Authenticator.MyAuthenticator() cannot be resolved".
It seems it doesn't like "MyAuthenticator()" when attempted to create the object.

Below is the java file that I put into a package called com.dva.Authenticator:



package com.dva.Authenticator;
 
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 = "myusername";
 
            // Get the password from the user...
            String password = "mypassword";
 
            // Return the information
            return new PasswordAuthentication(username, password.toCharArray());
        }
    }

Open in new window

0
 

Author Comment

by:cindymccartney
ID: 22908552
ok, just an update.  I got the classes to work correctly per CEHJ's example.  

However, I am getting a different error:

Access denied (java.net.NetPermission setDefaultAuthenticator)|#]
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 22908763
You've got a SecurityManager in place? Are you doing this inside a servlet container?
0
 

Author Comment

by:cindymccartney
ID: 22908892
I'm writing the code inside Sun's JCAPS application.

I'm not sure if there is a SecurityMangager in place or not.

I'm also not sure if the java collaboration inside of JCAPS is considered a servlet container.
0
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 2000 total points
ID: 22909074
Check out

http://java.sun.com/javase/6/docs/api/java/lang/SecurityManager.html

since you need to know whether you've got one or not. My guess is that you have. If so, you have two basic alternatives:

a. give the code the permission required
b. disable it
0
 

Author Comment

by:cindymccartney
ID: 22909492
Thanks CEHJ for your continued help.

I do have a java.policy file (pasted below)  in one of the application server directories.  Do I need to add a permission entry into this file?

If so, can you give me an example of what it would look like?

Or maybe I'm not on the right track at all.

I'm not explicitly enabling the security manager, but it might be something the App server is enabling by default somehow.  Otherwise, how would I go about disabling it?

//
// @(#)src/security/sov/config/java.policy, security, asdev, 20050521 1.4
// ===========================================================================
// Licensed Materials - Property of IBM
// "Restricted Materials of IBM"
//
// IBM SDK, Java(tm) 2 Technology Edition, v1.4.2
// (C) Copyright IBM Corp. 1998, 2002. All Rights Reserved
// ===========================================================================
//
 
 
// Standard extensions get all permissions by default
 
grant codeBase "file:${java.home}/lib/ext/*" {
        permission java.security.AllPermission;
};
 
// default permissions granted to all domains
 
grant { 
        // Allows any thread to stop itself using the java.lang.Thread.stop()
        // method that takes no argument.
        // Note that this permission is granted by default only to remain
        // backwards compatible.
        // It is strongly recommended that you either remove this permission
        // from this policy file or further restrict it to code sources
        // that you specify, because Thread.stop() is potentially unsafe.
        // See "http://java.sun.com/notes" for more information.
        permission java.lang.RuntimePermission "stopThread";
 
        // allows anyone to listen on un-privileged ports
        permission java.net.SocketPermission "localhost:1024-", "listen";
 
        // "standard" properies that can be read by anyone
 
        permission java.util.PropertyPermission "java.version", "read";
        permission java.util.PropertyPermission "java.vendor", "read";
        permission java.util.PropertyPermission "java.vendor.url", "read";
        permission java.util.PropertyPermission "java.class.version", "read";
        permission java.util.PropertyPermission "os.name", "read";
        permission java.util.PropertyPermission "os.version", "read";
        permission java.util.PropertyPermission "os.arch", "read";
        permission java.util.PropertyPermission "file.separator", "read";
        permission java.util.PropertyPermission "path.separator", "read";
        permission java.util.PropertyPermission "line.separator", "read";
 
        permission java.util.PropertyPermission "java.specification.version", "read";
        permission java.util.PropertyPermission "java.specification.vendor", "read";
        permission java.util.PropertyPermission "java.specification.name", "read";
 
        permission java.util.PropertyPermission "java.vm.specification.version", "read";
        permission java.util.PropertyPermission "java.vm.specification.vendor", "read";
        permission java.util.PropertyPermission "java.vm.specification.name", "read";
        permission java.util.PropertyPermission "java.vm.version", "read";
        permission java.util.PropertyPermission "java.vm.vendor", "read";
        permission java.util.PropertyPermission "java.vm.name", "read";
 
};

Open in new window

0
 

Author Comment

by:cindymccartney
ID: 22936847
Just an update, I was able to get it working.  Here is what I needed to add to my server.policy file:

Replace the following line:
   permission java.util.PropertyPermission "*", "read"; with
   permission java.util.PropertyPermission "*", "read,write";

And then within the same grant clause as the above add the following line:

permission java.net.NetPermission "setDefaultAuthenticator"
0
 

Author Closing Comment

by:cindymccartney
ID: 31514259
Thanks CEHJ for your help!
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 22937790
Good - glad it's working :-)
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
Suggested Courses
Course of the Month11 days, 12 hours left to enroll

564 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question