5

My Client should receive a File from the Controller. The problem is that the Client is only receiving a string. How can I get the returned stream from the Controller?

This is my Controller:

@Get("/{databaseName}")
MutableHttpResponse < Object > createDatabaseBackup(String databaseName) {
    InputStream inputStreamDatabaseBackup = backupTask.exportBackup(databaseName);
    return HttpResponse.ok(new StreamedFile(inputStreamDatabaseBackup, MediaType.APPLICATION_OCTET_STREAM_TYPE));
}

Here is my Client:

@Inject
@Client("${agent.connection-url}")
private RxHttpClient client;

public String getBackup(String dataBaseName) {
    return client.toBlocking().retrieve(HttpRequest.GET("/backup/" + dataBaseName));
}
Daniel Widdis
  • 8,424
  • 13
  • 41
  • 63
davebo92123
  • 95
  • 2
  • 9

1 Answers1

6

You have to define that you need response as a byte[] array:

public byte[] getBackup(String databaseName) {
    return client.toBlocking().retrieve(HttpRequest.GET("/backup/" + databaseName), byte[].class);
}

Then you can convert byte array into any stream you want.

Or you can use the reactive way:

public Single<byte[]> getBackup(String databaseName) {
    return client.retrieve(HttpRequest.GET("/backup/" + databaseName), byte[].class)
        .collect(ByteArrayOutputStream::new, ByteArrayOutputStream::writeBytes)
        .map(ByteArrayOutputStream::toByteArray);
}

Or you can define declarative client:

@Client("${agent.connection-url}")
public interface SomeControllerClient {

    @Get(value = "/{databaseName}", processes = MediaType.APPLICATION_OCTET_STREAM)
    Flowable<byte[]> getBackup(String databaseName);

}

And then use it where you need:

@Inject
SomeControllerClient client;

public void someMethod() {
    client.getBackup("some-database")
        .collect(ByteArrayOutputStream::new, ByteArrayOutputStream::writeBytes)
        .map(ByteArrayOutputStream::toByteArray)
        .otherStreamProcessing...
}
cgrim
  • 4,890
  • 1
  • 23
  • 42
  • I'm glad it worked for you. Can you then please [accept the answer](https://meta.stackexchange.com/a/5235/789510)? It can help others when solving the same problem ;-) Thanks – cgrim Jun 19 '20 at 17:18