GPResponse.java 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package cn.hhj.http;
  2. import io.netty.buffer.Unpooled;
  3. import io.netty.channel.ChannelHandlerContext;
  4. import io.netty.handler.codec.http.*;
  5. public class GPResponse {
  6. //SocketChannel的封装
  7. private ChannelHandlerContext ctx;
  8. private HttpRequest req;
  9. public GPResponse(ChannelHandlerContext ctx, HttpRequest req) {
  10. this.ctx = ctx;
  11. this.req = req;
  12. }
  13. public void write(String out) throws Exception {
  14. try {
  15. if (out == null || out.length() == 0) {
  16. return;
  17. }
  18. // 设置 http协议及请求头信息
  19. FullHttpResponse response = new DefaultFullHttpResponse(
  20. // 设置http版本为1.1
  21. HttpVersion.HTTP_1_1,
  22. // 设置响应状态码
  23. HttpResponseStatus.OK,
  24. // 将输出值写出 编码为UTF-8
  25. Unpooled.wrappedBuffer(out.getBytes("UTF-8")));
  26. response.headers().set("Content-Type", "text/html;");
  27. // 当前是否支持长连接
  28. // if (HttpUtil.isKeepAlive(r)) {
  29. // // 设置连接内容为长连接
  30. // response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
  31. // }
  32. ctx.write(response);
  33. } finally {
  34. ctx.flush();
  35. ctx.close();
  36. }
  37. }
  38. }