Downloading a zip-file with URLConnection

Posted on 2008-09-30
Last Modified: 2008-11-07
Hi, I'm trying to download a zip-file with an URLConnection. But returns always -1.If I use another address to a normal html-page, it works. See my code below.
Can anyone help?

            URL url = new URL(address);

            outputStream = new BufferedOutputStream(new FileOutputStream(localFileName));

            URLConnection urlConnection = url.openConnection();


            inputStream = urlConnection.getInputStream();

            byte[] buffer = new byte[1024];

            int numRead;

            long numWritten = 0;

            while ((numRead = != -1)


                outputStream.write(buffer, 0, numRead);

                numWritten += numRead;



Open in new window

Question by:bueschi
  • 3
  • 2
LVL 23

Expert Comment

ID: 22606267
Are you able to download the zip page from browser? and from tools like wget, curl?

Author Comment

ID: 22606472
Hi Ajay-Singh, thank you for your question. For sure, with the browser, its no problem for downloading the file.I have not installed a tool like wget or curl.
LVL 23

Expert Comment

ID: 22611379
Can you set the request property to use browser's user-agent,

urlConnection.setRequestProperty("User-Agent", "Mozilla/4.0");

Author Comment

ID: 22681977
Hi Ajay-Singh, sorry, that I havent answer your question. We have new firewall sittings in our company, I tried it over vpn and we are going to solve the dowload with mule. So my problem is obsolete. Sorry and thanks

Accepted Solution

bueschi earned 0 total points
ID: 22864933
Finally I found a solution with the help of jakarta commons http client:
public String downloadFile(final String uri,

                           final String localFilePath,

                           final LogInformation logInformation)


    HttpClient client = new HttpClient();

    HostConfiguration config = new HostConfiguration();

    config.setProxy(PROXY_ADDRESS, PROXY_PORT);

    Credentials defaultcreds = new UsernamePasswordCredentials(PROXY_USER, PROXY_PASSWORD);

    client.getState().setProxyCredentials(AuthScope.ANY, defaultcreds);


    List<String> authPrefs = new ArrayList<String>(1);


    // This will exclude the NTLM authentication scheme

    client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);

    GetMethod method = new GetMethod(uri);

    OutputStream outputStream = null;

    String fileNameWithPath = null;

    // Provide custom retry handler is necessary


                                    new DefaultHttpMethodRetryHandler(3, false));

    InputStream responseBody = null;



        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK)


            log.error(logInformation, "Method failed: " + method.getStatusLine());


        responseBody = method.getResponseBodyAsStream();

        fileNameWithPath = localFilePath + extractFileName(method.getPath());

        outputStream = new BufferedOutputStream(new FileOutputStream(fileNameWithPath));, "write the file: '" + fileNameWithPath + "'.");

        IOUtils.copy(responseBody, outputStream);




    catch (HttpException e)


        String message = "A HttpException on downloading the shab archive: " + e.getMessage();

        log.error(logInformation, message, e);

        throw new RuntimeException(message);


    catch (IOException e)


        String message = "A IOException on downloading the shab archive: " + e.getMessage();

        log.error(logInformation, message, e);

        throw new RuntimeException(message);




        // Release the connection.



    return fileNameWithPath;



 * Extracts the file name.


 * @param path the path containing the name of the file.

 * @return the name of the file.


private String extractFileName(String path)


    String[] splits = path.split("/");

    String filename = splits[splits.length - 1];

    return filename;


Open in new window


Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
How can I do a Massively massive community reviewing-and-grading site? 7 70
Java and GPO 11 71
get weblogic logged in user in java 2 58
Groovy:unable to resolve class error 2 70
For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…

867 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now