MessageBodyWriter not found StreamingBodyResponse

269 Views Asked by At

I am trying to make StreamResponseBody work with sample hardcoded data.

@POST
@Path("filetypecsv")
@Produces("text/plain")
public ResponseEntity<StreamingResponseBody> studentsFile() {
    String name = "name";
    String rollNo = "rollNo";    

    StreamingResponseBody stream = output -> {
        Writer writer = new BufferedWriter(new OutputStreamWriter(output));
        writer.write("name,rollNo"+"\n");
            for (int i = 1; i <= 1000; i++) {
                writer.write(name + i + " ," + rollNo  + i + "\n");
                writer.flush();
            }
    };

    return  ResponseEntity.ok()
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=students.csv")
        .contentType(org.springframework.http.MediaType.TEXT_PLAIN)
            .body(stream);
}

I am always getting this error :

SEVERE: MessageBodyWriter not found for media type=text/plain, type=class org.springframwork.http.ResponseEntity, genericType=org.springframework.http.ReponseEntity<StreamingResponseBody>.

I have added the dependency : jersey-media-json-jackson.

But I am still getting this error, please advise.

1

There are 1 best solutions below

0
On

This solution applies if your code is using Jax.rs.core and not Spring @RestController. I have not seen a solution where you can use Springs StreamingResponseBody along with jax.rs But instead you can use jax.rs StreamingOutput. You can return a jax.rs Response, and (MediaType.TEXT_PLAIN) or equivalent like an octet stream.

Please see this link - https://dzone.com/articles/jax-rs-streaming-response

  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();