# Downloading Files from HTTP Network in Java
Here's how to download files from an HTTP server using Java, specifying the IP address and port:
## Basic HTTP File Download
```java
import java.io.*;
import java.net.*;
public class HttpFileDownloader {
public static void downloadFile(String fileURL, String savePath) throws IOException {
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
// Check if the response is OK (HTTP 200)
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
// Extract filename from Content-Disposition header
if (disposition != null) {
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
} else {
// If no Content-Disposition, extract from URL
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1);
}
// Open input stream from the HTTP connection
InputStream inputStream = httpConn.getInputStream();
// Create output stream to save file
FileOutputStream outputStream = new FileOutputStream(savePath + fileName);
int bytesRead;
byte[] buffer = new byte[4096];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("File downloaded to: " + savePath + fileName);
} else {
System.out.println("No file to download. Server replied HTTP code: " + responseCode);
}
httpConn.disconnect();
}
public static void main(String[] args) {
try {
// Example usage:
// http://server-ip:port/path/to/file
downloadFile("http://192.168.1.100:8080/files/document.pdf", "downloads/");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
```
## Advanced Version with Progress Tracking
```java
import java.io.*;
import java.net.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public class AdvancedHttpDownloader {
public static void downloadWithProgress(String fileURL, String saveDir)
throws IOException {
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setRequestMethod("GET");
// Get file size for progress tracking
int fileSize = httpConn.getContentLength();
try (InputStream in = httpConn.getInputStream()) {
// Create save directory if it doesn't exist
Files.createDirectories(Paths.get(saveDir));
// Get filename from URL
String fileName = fileURL.substring(fileURL.lastIndexOf('/') + 1);
String filePath = saveDir + File.separator + fileName;
// Download with progress tracking
try (OutputStream out = new FileOutputStream(filePath)) {
byte[] buffer = new byte[1024];
int bytesRead;
long totalBytesRead = 0;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
totalBytesRead += bytesRead;
// Calculate and display progress
if (fileSize > 0) {
int progress = (int) (totalBytesRead * 100 / fileSize);
System.out.printf("Download progress: %d%%\r", progress);
}
}
}
System.out.println("\nDownload completed: " + filePath);
} finally {
httpConn.disconnect();
}
}
public static void main(String[] args) {
try {
// Example: http://server-ip:port/path/to/file
downloadWithProgress("http://192.168.1.100:8080/files/largefile.zip", "downloads");
} catch (IOException ex) {
System.err.println("Download failed: " + ex.getMessage());
}
}
}
```
## Using Java 11+ HttpClient (Modern Approach)
```java
import java.net.URI;
import java.net.http.*;
import java.net.http.HttpResponse.BodyHandlers;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public class ModernHttpDownloader {
public static void downloadFile(String fileURL, String savePath) throws Exception {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(fileURL))
.build();
// Send async request and handle response
client.sendAsync(request, BodyHandlers.ofFile(Paths.get(savePath)))
.thenApply(HttpResponse::body)
.thenAccept(path -> System.out.println("File saved to: " + path))
.exceptionally(e -> {
System.err.println("Download failed: " + e.getMessage());
return null;
})
.join(); // Wait for completion
}
public static void main(String[] args) {
try {
// Example: http://server-ip:port/path/to/file
downloadFile("http://192.168.1.100:8080/files/image.jpg", "downloads/image.jpg");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
```
## Important Notes:
1. **IP and Port Format**: The URL should be in format `http://[ip-address]:[port]/path/to/file`
- Example: `http://192.168.1.100:8080/files/document.pdf`
2. **Error Handling**: Always implement proper error handling for:
- Network connectivity issues
- Invalid URLs
- File permission problems
- Server-side errors
3. **Security Considerations**:
- Validate URLs to prevent SSRF attacks
- Set timeout values to avoid hanging
- Consider HTTPS for secure transfers
4. **Performance Tips**:
- Use buffered streams for better performance
- For large files, consider resumable downloads
- Implement connection pooling for multiple downloads
Would you like me to explain any specific part in more detail or adapt any of these examples for a particular use case?
No comments:
Post a Comment