Optimize time for file download 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 -&gt;
    URLConnection url = new URL(remoteUrl).openConnection()
    def remoteAuth = "Basic " + "${username}:${password}".getBytes().encodeBase64().toString()
    url.setRequestProperty("Authorization", remoteAuth);
        if (url.responseCode == 200) {
            out &lt;&lt; url.getInputStream()
        } else {
            System.out.println("Can not download file from ${remoteUrl}")
        }
}
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 -&gt;
    remoteUrl.toURL()
        .getText(requestProperties: [Authorization: authorization])
        .bytes.with { out &lt;&lt; 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 -&gt;
    remoteUrl.toURL().openConnection().with {
      setRequestProperty 'Authorization', 'Basic' + "$username:$password".bytes.encodeBase64().toString()
      if (200 == it.responseCode) {
        out &lt;&lt; it.inputStream
      }
      else {
        throw new ConnectException("Cannot download file from ${remoteUrl}")
      }
    }
  }
}