Sending And Receiving Streams With JAX-RS 📎
Streaming:
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.StreamingOutput;
@Path("XYZ)
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public class XYZResource {
@GET
public StreamingOutput streamFile() {
final Random random = new Random();
return new StreamingOutput() {
@Override
public void write(OutputStream output)
throws IOException, WebApplicationException {
output.write(/* 42 */);
}
};
}
}
Receiving:
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
//...
public class XYZResourceIT {
private Client client;
private WebTarget tut;
@Before
public void init() {
this.client = ClientBuilder.newClient();
this.tut = this.client.target("http://...");
}
@Test
public void downloadFileWithDefaultSize() throws IOException {
int defaultSize = 10;
try (InputStream stream = this.tut.
request(MediaType.APPLICATION_OCTET_STREAM).
get(InputStream.class);) {
assertNotNull(stream);
//process stream
}
}
}
See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting