Response.java 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package cn.nosum.http;
  2. import com.alibaba.fastjson.JSONObject;
  3. import io.netty.buffer.Unpooled;
  4. import io.netty.channel.ChannelHandlerContext;
  5. import io.netty.handler.codec.http.*;
  6. import java.nio.charset.StandardCharsets;
  7. public class Response {
  8. // SocketChannel的封装
  9. private ChannelHandlerContext ctx;
  10. private HttpRequest req;
  11. public Response(ChannelHandlerContext ctx, HttpRequest req) {
  12. this.ctx = ctx;
  13. this.req = req;
  14. }
  15. public void write(JSONObject out) throws Exception {
  16. try {
  17. if (out == null) {
  18. return;
  19. }
  20. // 设置 http协议及请求头信息
  21. FullHttpResponse response = new DefaultFullHttpResponse(
  22. // 设置http版本为1.1
  23. HttpVersion.HTTP_1_1,
  24. // 设置响应状态码
  25. HttpResponseStatus.OK,
  26. // 将输出值写出 编码为UTF-8
  27. Unpooled.wrappedBuffer(out.toJSONString().getBytes(StandardCharsets.UTF_8)));
  28. response.headers().set("Content-Type", "application/json;");
  29. ctx.writeAndFlush(response);
  30. } finally {
  31. ctx.close();
  32. }
  33. }
  34. }