Solved

Downloading a zip-file with URLConnection

Posted on 2008-09-30
5
808 Views
Last Modified: 2008-11-07
Hi, I'm trying to download a zip-file with an URLConnection. But inputStream.read(buffer)) returns always -1.If I use another address to a normal html-page, it works. See my code below.
Can anyone help?
Thanks
...
            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 = inputStream.read(buffer)) != -1)
            {
                outputStream.write(buffer, 0, numRead);
                numWritten += numRead;
            }
...

Open in new window

0
Comment
Question by:bueschi
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
5 Comments
 
LVL 23

Expert Comment

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

Author Comment

by:bueschi
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.
0
 
LVL 23

Expert Comment

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

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

Author Comment

by:bueschi
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
0
 

Accepted Solution

by:
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);
    client.setHostConfiguration(config);
 
    List<String> authPrefs = new ArrayList<String>(1);
    authPrefs.add(AuthPolicy.BASIC);
    // 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
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                                    new DefaultHttpMethodRetryHandler(3, false));
 
    InputStream responseBody = null;
    try
    {
        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));
        log.info(logInformation, "write the file: '" + fileNameWithPath + "'.");
        IOUtils.copy(responseBody, outputStream);
        outputStream.close();
        responseBody.close();
    }
    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);
    }
    finally
    {
        // Release the connection.
        method.releaseConnection();
    }
    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

0

Featured Post

Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
going to wrong jsp page 2 68
Problem to Alipay 10 94
Notify sent to other threads in Java 9 54
Setup Eclipse for Andriod development 2 18
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
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 learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
The viewer will learn how to implement Singleton Design Pattern in Java.
Suggested Courses

739 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