Skip to content

Commit

Permalink
add download function [#2]
Browse files Browse the repository at this point in the history
  • Loading branch information
GreenBloodDev committed Oct 4, 2023
1 parent 5499faf commit 8ad84d8
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions src/main/java/pl/nightdev701/http/HttpRequestHandler.java
Original file line number Diff line number Diff line change
@@ -1,18 +1,34 @@
package pl.nightdev701.http;

import pl.nightdev701.logger.AbstractLogger;
import pl.nightdev701.logger.standard.DefaultLogger;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.logging.Level;

public class HttpRequestHandler {

private final String url;
private final AbstractLogger logger;
private String body;

public HttpRequestHandler(String url) {
this.logger = new DefaultLogger();
this.url = url;
}

public HttpRequestHandler(String url, AbstractLogger logger) {
this.url = url;
this.logger = logger;
}

/**
Expand All @@ -33,6 +49,39 @@ public void request() {
}
}

/**
* Download file
*/
public void download(String output) {

String link = url;

logger.log(Level.INFO, "Download file to path: " + output);

URL url;
try {
url = new URL(link);
try (
InputStream inputStream = url.openStream();
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
FileOutputStream fileOutputStream = new FileOutputStream(output)
) {
byte[] bucket = new byte[2048];
int numBytesRead;

while ((numBytesRead = bufferedInputStream.read(bucket, 0, bucket.length)) != -1) {
fileOutputStream.write(bucket, 0, numBytesRead);
}
} catch (IOException e) {
logger.log(Level.WARNING, "Download failed: " + e.getMessage());
}
logger.log(Level.INFO, "Download complete!");
} catch (MalformedURLException e) {
logger.log(Level.WARNING, "Download failed: " + e.getMessage());
throw new RuntimeException(e);
}
}

/**
* read body
*/
Expand Down

0 comments on commit 8ad84d8

Please sign in to comment.