Groovy Download File From Url With Authentication Link Site
Downloading a file from a URL using Groovy is a common task, but adding authentication—whether , Bearer Tokens , or Cookies —requires specific configurations. Depending on your needs, you can use built-in Java classes, standard Groovy extensions, or specialized libraries like HTTPBuilder-NG . 1. Basic Authentication (Built-in Classes)
def cookieString = "JSESSIONID=ABC123XYZ; otherCookie=value" def connection = new URL("https://example.com").openConnection() connection.setRequestProperty("Cookie", cookieString) new File("report.csv").withOutputStream { out -> out << connection.inputStream } Use code with caution. 4. Advanced: Using HTTPBuilder-NG
For simple use cases without external dependencies, you can use native Java URLConnection or the Authenticator class. Method A: Setting the Authorization Header groovy download file from url with authentication
If you need to download a file after a manual login (like through a browser session), you may need to pass session cookies.
def user = "yourUsername" def password = "yourPassword" def downloadUrl = "https://example.com" def outputFile = new File("downloaded_file.zip") def authString = "${user}:${password}".getBytes().encodeBase64().toString() def connection = new URL(downloadUrl).openConnection() connection.setRequestProperty("Authorization", "Basic ${authString}") outputFile.withOutputStream { out -> out << connection.inputStream } Use code with caution. Method B: Using java.net.Authenticator Downloading a file from a URL using Groovy
def token = "your_bearer_token_here" def url = new URL("https://example.com") def connection = url.openConnection() connection.setRequestProperty("Authorization", "Bearer $token") connection.setRequestProperty("Accept", "application/octet-stream") new File("secure_document.pdf").withOutputStream { out -> out << connection.inputStream } Use code with caution. 3. Session-Based (Cookie) Authentication
This is often the most direct method. You manually encode the credentials and set them in the request header. You manually encode the credentials and set them
For complex projects, using a library like is recommended for its high-level DSL and robust error handling.