diff --git a/pom.xml b/pom.xml
index 2de2f3a..7c6afa5 100644
--- a/pom.xml
+++ b/pom.xml
@@ -27,5 +27,11 @@
httpclient5-fluent
5.2.1
+
+ junit
+ junit
+ 4.13.2
+ test
+
diff --git a/src/main/java/com/imyeyu/network/ProgressiveRequest.java b/src/main/java/com/imyeyu/network/ProgressiveRequest.java
index 8552330..80070f7 100644
--- a/src/main/java/com/imyeyu/network/ProgressiveRequest.java
+++ b/src/main/java/com/imyeyu/network/ProgressiveRequest.java
@@ -1,9 +1,13 @@
package com.imyeyu.network;
import com.imyeyu.io.IO;
+import com.imyeyu.java.TimiJava;
import org.apache.hc.client5.http.fluent.Request;
import org.apache.hc.client5.http.fluent.Response;
+import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.HttpEntity;
+import org.apache.hc.core5.http.HttpResponse;
+import org.apache.hc.core5.http.ProtocolException;
import org.apache.hc.core5.http.io.HttpClientResponseHandler;
import org.apache.hc.core5.http.io.entity.EntityUtils;
@@ -29,6 +33,10 @@ public class ProgressiveRequest {
this.callback = callback;
}
+ public static ProgressiveRequest wrap(Request request) {
+ return new ProgressiveRequest(request, null);
+ }
+
public static ProgressiveRequest wrap(Request request, ProgressiveCallback callback) {
return new ProgressiveRequest(request, callback);
}
@@ -43,6 +51,19 @@ public class ProgressiveRequest {
return os.toByteArray();
}
+ public long length() throws IOException, ProtocolException {
+ HttpResponse response = request.execute().returnResponse();
+ final int status = response.getCode();
+ if (status < 200 || 300 <= status) {
+ throw new IOException("HTTP error status: " + status);
+ }
+ final Header contentLengthHeader = response.getHeader("Content-Length");
+ if (contentLengthHeader == null) {
+ throw new IOException("Content-Length header missing");
+ }
+ return Long.parseLong(contentLengthHeader.getValue());
+ }
+
private void processResponse(Response response, OutputStream os) throws IOException {
response.handleResponse((HttpClientResponseHandler) resp -> {
HttpEntity entity = resp.getEntity();
@@ -55,14 +76,18 @@ public class ProgressiveRequest {
}
long length = entity.getContentLength();
- IO.toOutputStream(entity.getContent(), os, new IO.OnWriteCallback() {
+ if (TimiJava.isEmpty(callback)) {
+ IO.toOutputStream(entity.getContent(), os);
+ } else {
+ IO.toOutputStream(entity.getContent(), os, new IO.OnWriteCallback() {
- @Override
- public boolean handler(long total, long now) {
+ @Override
+ public boolean handler(long total, long now) {
- return callback.handler(length, total, now);
- }
- });
+ return callback.handler(length, total, now);
+ }
+ });
+ }
EntityUtils.consume(entity);
return null;
});