add length() for ProgressiveRequest
This commit is contained in:
6
pom.xml
6
pom.xml
@ -27,5 +27,11 @@
|
||||
<artifactId>httpclient5-fluent</artifactId>
|
||||
<version>5.2.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.13.2</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
|
||||
@ -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<Void>) resp -> {
|
||||
HttpEntity entity = resp.getEntity();
|
||||
@ -55,6 +76,9 @@ public class ProgressiveRequest {
|
||||
}
|
||||
long length = entity.getContentLength();
|
||||
|
||||
if (TimiJava.isEmpty(callback)) {
|
||||
IO.toOutputStream(entity.getContent(), os);
|
||||
} else {
|
||||
IO.toOutputStream(entity.getContent(), os, new IO.OnWriteCallback() {
|
||||
|
||||
@Override
|
||||
@ -63,6 +87,7 @@ public class ProgressiveRequest {
|
||||
return callback.handler(length, total, now);
|
||||
}
|
||||
});
|
||||
}
|
||||
EntityUtils.consume(entity);
|
||||
return null;
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user