This is the working code snippet to download file from a URL. I want to know if there is any optimization I can do to download the file faster.

File localFile = new File(localUrl)
localFile.withOutputStream { out ->
    URLConnection url = new URL(remoteUrl).openConnection()
    def remoteAuth = "Basic " + "${username}:${password}".getBytes().encodeBase64().toString()
    url.setRequestProperty("Authorization", remoteAuth);
        if (url.responseCode == 200) {
            out << url.getInputStream()
        } else {
            System.out.println("Can not download file from ${remoteUrl}")
        }
}
  • 4
    You mean aside from "get a better internet speed", right? – Dan Pantry Sep 29 '15 at 12:53
  • Yes.......... :) – Debmalya Biswas Sep 29 '15 at 12:58

You won't be able to see speed improvements here, as that's just network limited, but there are a few improvements to this snippet of code I can suggest (wrapped in a method):

def static copyToLocalUrl(final String localUrl, final String remoteUrl, final String username, final String password) {
  final def authorization = 'Basic' + "$username:$password".bytes.encodeBase64().toString()
  new File(localUrl).withOutputStream { final out ->
    remoteUrl.toURL()
        .getText(requestProperties: [Authorization: authorization])
        .bytes.with { out << it }
  }
}

Note that you don't need to enclose GString variables in brackets if you're simply just accessing them or their fields.

This answer also doesn't do any HTTP response checking for simplicity; it just saves the HTML to a local file. If you're keen on checking the response, you can do so like this:

def static copyToLocalUrl(final String localUrl, final String remoteUrl, final String username, final String password) {
  new File(localUrl).withOutputStream { final out ->
    remoteUrl.toURL().openConnection().with {
      setRequestProperty 'Authorization', 'Basic' + "$username:$password".bytes.encodeBase64().toString()
      if (200 == it.responseCode) {
        out << it.inputStream
      }
      else {
        throw new ConnectException("Cannot download file from ${remoteUrl}")
      }
    }
  }
}

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.