我想使用netty http服务器发送json响应。我使用Gson进行json创建。我的代码看起来像这样

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


在channelRead0方法中,以及

ctx.flush()


在channelReadComplete方法中。问题是,我再也没有得到响应,似乎请求被卡住了,并且从不返回响应。我相信这与内容的长度有关。我需要做更多的事情吗?

最佳答案

您需要构造FullHttpResponse或通过编写LastHttpContent结束HttpReponse。

09-12 11:37