How to Download a File from a URL in Java
Aspose.HTML for Java
exposes a network service through the context of an HTMLDocument. Create a Url, send a RequestMessage through document.getContext().getNetwork(), verify the ResponseMessage, and write the returned bytes to a local path.
This workflow is useful when a Java application already loads or processes HTML and must download a resource discovered in a document, such as an image, stylesheet, archive, or linked file. The same network context can be used for direct resource URLs without loading a web page first.
Save the Downloaded File in Java
The following Java example downloads a PNG file from a known URL and saves it in the output directory. It uses standard java.nio.file classes for local file operations, so the snippet does not depend on a separate example helper class.
Download File from URL in Java
Path outputDirectory = Paths.get("output");
Files.createDirectories(outputDirectory);
Url fileUrl = new Url("https://docs.aspose.com/html/images/handlers/message-handlers.png");
try (HTMLDocument document = new HTMLDocument()) {
// Send a request through the document network service
RequestMessage request = new RequestMessage(fileUrl);
ResponseMessage response = document.getContext().getNetwork().send(request);
if (!response.isSuccess()) {
throw new IllegalStateException("The file could not be downloaded");
}
// Derive the local file name from the URL path
String fileName = Paths.get(fileUrl.getPathname())
.getFileName()
.toString();
Path outputPath = outputDirectory.resolve(fileName);
// Save the response body to the local file system
Files.write(outputPath, response.getContent().readAsByteArray());
System.out.println("Saved to " + outputPath);
}
Steps to Download a File from a URL
- Create an empty
HTMLDocumentto access its network context. - Create a
Urlfor the remote resource. - Pass the URL to
RequestMessageand send the request through the document network service. - Check
ResponseMessage.isSuccess()before reading the response body. - Derive a file name from the URL path and save the returned bytes with
Files.write().
After the code runs, the downloaded resource is available as output/message-handlers.png.
When to Use the Aspose.HTML Network API
Use this approach when downloading a file is part of an HTML-processing workflow. For example, the application may first find an image URL in an src attribute, resolve a relative reference against the document base URI, and then request the resource through the same document context.
For a standalone HTTP download unrelated to HTML parsing or document resources, use the HTTP client already adopted by your Java application. The Aspose.HTML workflow is most useful when DOM navigation, URL resolution, resource extraction, and downloading belong to the same operation.
Read Save File from URL Using Aspose.HTML for Java for the corresponding documentation example.
File Download Considerations
- Check the response before saving it. A URL may return an error page, redirect, or unavailable resource instead of the expected file.
- Choose the local file name deliberately. The example uses the final segment of the URL path. Use an explicit name when the path is empty or the server provides a different name in response headers.
- Prevent accidental overwrites. Different URLs can have the same final path segment, so generate unique names when downloading multiple resources.
- Plan for large files.
readAsByteArray()keeps the complete response in memory. Use a streaming download strategy when the expected resources are too large to buffer safely. - Validate untrusted URLs. Restrict allowed schemes and hosts when URLs come from users or external documents, and write files only inside an approved output directory.
- Respect copyright and website terms. Download and reuse only files that you own or are authorized to access. A publicly accessible URL does not by itself grant permission to copy, redistribute, or use the file commercially.
FAQ
1. Why does the example create an empty HTMLDocument?
HTMLDocument provides the browsing context that exposes the Aspose.HTML network service. The document can be empty when the application already knows the resource URL and does not need to parse a web page first.
2. Can the Java API download file types other than images?
Yes. The network service returns the response body as bytes, so the same workflow can save documents, archives, stylesheets, images, or other resources available through a supported URL. The application remains responsible for validating the response and choosing the correct file name and extension.
3. Can I download a file referenced by a relative URL in HTML?
Yes. Read the resource path from an attribute such as src or href, then resolve it against document.getBaseURI() with new Url(relativePath, document.getBaseURI()) before creating the request.
4. How can Java download multiple files found in one HTML document?
Collect the required resource URLs from the DOM, resolve each relative reference, and send a separate RequestMessage for every URL through the same document network service. Assign unique output names when different URLs end with the same file name.
Install Aspose.HTML for Java
Add Aspose.HTML for Java from the official Aspose repository. Replace ASPOSE_HTML_VERSION with an exact version from the
Aspose.HTML for Java releases
page, then reload or rebuild the project so the dependency is resolved.
Add the repository and dependency to the Maven project:
Maven – pom.xml
<repositories>
<repository>
<id>AsposeJavaAPI</id>
<url>https://releases.aspose.com/java/repo/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-html</artifactId>
<version>ASPOSE_HTML_VERSION</version>
</dependency>
</dependencies>Add the repository and dependency to the Gradle project:
Gradle – build.gradle
repositories {
maven {
url = uri('https://releases.aspose.com/java/repo/')
}
}
dependencies {
implementation 'com.aspose:aspose-html:ASPOSE_HTML_VERSION'
}Use a JDK compatible with the selected release. For manual JAR installation, Kotlin DSL, updates, and dependency troubleshooting, see Install Aspose.HTML for Java .
Related Java Data Extraction Tasks
Continue with HTML data extraction, image downloads, SVG extraction, or the Aspose.HTML for Java API overview.