Gray
Gray

Reputation: 116878

How to set the content-type when I render my own response in a CXF @WebMethod

I'm having problems setting the Content-Type when I do my own rendering inside of a CXF (v2.6.3) @WebMethod.

The following pattern works fine:

@Path("/foo")
@WebService
public class FooService {
    @Path("/bar")
    @Produces({ "text/plain" })
    @GET
    @WebMethod
    public String bar() {
        return "hi";
    }

This returns "hi" to the http-client with a Content-Type: Content-Type: text/plain header which is what I expect.

However, when I try to do my own rendering by using the response OutputStream, "hi" is properly returned but the @Produces annotation is ignored and the default text/xml content-type is returned. This is true even if I call setContentType(...) myself.

@Path("/heartbeat2")
@Produces({ "text/plain" })
@WebMethod
@Get
public void heartbeat2() {
    HttpServletResponse response = messageCtx.getHttpServletResponse();
    response.getOutputStream().write("hi".getBytes());
    // fails with or without this line
    response.setContentType("text/plain");
}

Here's the output:

HTTP/1.1 200 OK
Content-Type: text/xml
Content-Length: 2
Connection: keep-alive
Server: Jetty(8.1.9.v20130131)

hi

Any idea how I can render my own output directly to the output-stream and set the content-type appropriately? Thanks in advance.

Upvotes: 2

Views: 2707

Answers (1)

nadirsaghar
nadirsaghar

Reputation: 577

I don't see anything wrong with what you are doing. At the very least setting content-type in HttpServletResponse should work. Anyways, you can have more control over what you return if you use javax.ws.rs.core.Response . See if this works :

@Path("/foo")
@WebService
public class FooService {
    @Path("/bar")
    @GET
    @WebMethod
    public Response bar() {
        return Response.ok().type("text/plain").entity("hi").build();
    }
    ...

Upvotes: 3

Related Questions