Apostolos
Apostolos

Reputation: 8121

Json response in netty and java

I want to send a json response using a netty http server. I use Gson for the json creation. My code looks like that

HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            HttpResponseStatus.OK);
response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, 0);
response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/json");
JsonObject jsonResponseMessage = new JsonObject();
jsonResponseMessage.addProperty("result", success);
ctx.write(jsonResponseMessage);
response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, jsonResponseMessage.toString().length());
ctx.write(response);

inside channelRead0 method, and

ctx.flush()

inside channelReadComplete method. The problem is that the I never get the response, back, it seems that the request gets stuck and never return a response. I believe it has to do with the content length. Do I need to do something more?

Upvotes: 0

Views: 1750

Answers (2)

FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(here_your_data_as_byte_array));
response .headers().set(CONTENT_TYPE, "application/json");
response .headers().set(CONTENT_LENGTH, response .content().readableBytes());
ctx.write(response );
ctx.flush();

Upvotes: 0

Norman Maurer
Norman Maurer

Reputation: 23567

You need to construct a FullHttpResponse or end the HttpReponse by writing a LastHttpContent.

Upvotes: 1

Related Questions