@Grab('org.apache.httpcomponents:httpclient:4.5.13') import org.apache.httpclient.methods.HttpGet import org.apache.httpclient.impl.client.HttpClients def url = "https://example.com" def client = HttpClients.createDefault() def request = new HttpGet(url) client.execute(request).withCloseable { response -> if (response.statusLine.statusCode == 200) { new File("logo.png").withOutputStream { out -> response.entity.content.transferTo(out) } } } Use code with caution. Summary Comparison Table Complexity Quick scripts and simple image downloads. Java NIO High-performance file copying and modern Java apps. Authenticator URLs requiring Basic or Digest authentication. Apache HttpClient
The most "Groovy" way to download an image is using the withOutputStream and the left-shift ( << ) operator. This automatically manages the stream resources, ensuring they are closed after the operation.
#groovy #snippet. Downloading a file from a URL requiring user authentication with Groovy is as easy as: java. net. Authenticator. DEV Community Downloading Files With Groovy and Authentication
If the image is hosted behind a protected URL (e.g., a private API or a secure portal), you can set a default Authenticator before initiating the download.