问题
Consider the following example:
import java.io.InputStream;
import kong.unirest.GetRequest;
import kong.unirest.HttpResponse;
class Download {
private long byteCounter;
private long contentLength;
InputStream download(GetRequest request) {
// no appropriate method here? --v
HttpResponse response = request.???
// get length to display some progress bar later ...
// (not shown here)
long contentLength = contentLengthHeader != null
? Long.valueOf(contentLengthHeader)
: Long.valueOf(0);
InputStream responseInputStream = response.getBody();
return responseInputStream;
}
}
At the position marked ???
I can't figure out which method to call to be able to receive the response body as an InputStream
.
Something like request.asObject(InputStream.class)
doesn't work, as this method uses object-mappers to marshal the response into a Java class (and there of course isn't one for InputStream
).
回答1:
You can get the raw response input stream like this:
HttpResponse<InputStream> response = request.asObject(raw -> raw.getContent());
InputStream responseInputStream = response.getBody();
If you require that the input stream is not immediately closed after the lambda has been executed, then you need to use the async methods:
CompletableFuture<HttpResponse<InputStream>> responseFuture = request.asObjectAsync(raw -> raw.getContent());
HttpResponse<InputStream> response = responseFuture.get();
InputStream responseInputStream = response.getBody();
来源:https://stackoverflow.com/questions/57289844/how-to-receive-the-response-body-as-an-inputstream-in-unirest