问题
I have a workflow that involves doing a HTTP POST from my Java client to my web server. The body of the post has a specification object. I then pass that on from my webserver to Apache ZooKeeper (which runs in its own process on the server) that runs a big hairy calculation. I am struggling with figuring out how to send back the bytes to my webserver in streaming fashion. I need it to stream back because I have a HTTP GET request on my webserver from my Java client that is waiting to stream back the bytes. I cannot wait for the whole calculation to finish, I want bytes sent as soon as possible back to the client.
Most the examples online for JAX-RS that do a HTTP PUT from the client side and on the webserver side don't have examples for streaming code. I'll post what I have so far, but it doesn't work.
Here is my ZooKeeper Java code, which calls a JAX-RS client-side PUT. I am really unsure of how to do this, I have never tried streaming data with JAX-RS.
final Client client = ClientBuilder.newClient();
final WebTarget createImageTarget = client.target("groups/{imageGroupUuid:" + Regex.UUID + "}");
StreamingOutput imageResponse = createImageTarget.request(MediaType.APPLICATION_OCTET_STREAM).put(Entity.entity(createRandomImageDataBytes(imageConfigurationObject), MediaType.APPLICATION_OCTET_STREAM), StreamingOutput.class);
Here is my webserver code which handles the HTTP PUT. It is just a stub because I have no confidence in my client side HTTP PUT.
@PUT
@PATH("groups/{uuid:" + Regex.UUID + "}")
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
public void updateData(StreamingOutput streamingOutput)
{
}
回答1:
Try something like this:
@GET
@Produces(MediaType.TEXT_PLAIN)
@Path("/{arg}")
public Response get(@PathParam("arg") {
//get your data based on "arg"
StreamingOutput stream = new StreamingOutput() {
@Override
public void write(OutputStream os) throws IOException, WebApplicationException {
Writer writer = new BufferedWriter(new OutputStreamWriter(os));
for (org.neo4j.graphdb.Path path : paths) {
writer.write(path.toString() + "\n");
}
writer.flush();
}
};
return Response.ok(stream).build();
}
@PUT
@Consumes("application/octet-stream")
public Response putFile(@Context HttpServletRequest request,
@PathParam("fileId") long fileId,
InputStream fileInputStream) throws Throwable {
// Do something with the fileInputStream
// etc
}
来源:https://stackoverflow.com/questions/25922920/streaming-bytes-via-http-put-with-jax-rs