HttpRequestHandler.java 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package com.syjy.http;
  2. import io.netty.channel.ChannelFutureListener;
  3. import io.netty.channel.ChannelHandlerContext;
  4. import io.netty.channel.SimpleChannelInboundHandler;
  5. import io.netty.handler.codec.http.*;
  6. import lombok.extern.slf4j.Slf4j;
  7. import java.nio.charset.StandardCharsets;
  8. import java.util.Arrays;
  9. import java.util.List;
  10. @Slf4j
  11. public class HttpRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
  12. private static final List<String> NO_LOG_URL = Arrays.asList("/getAllPoints", "/", "/com/syjy/favicon.ico");
  13. @Override
  14. public void channelReadComplete(ChannelHandlerContext ctx) {
  15. ctx.flush();
  16. }
  17. @Override
  18. protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
  19. //100 Continue
  20. if (HttpUtil.is100ContinueExpected(req)) {
  21. ctx.write(new DefaultFullHttpResponse(
  22. HttpVersion.HTTP_1_1,
  23. HttpResponseStatus.CONTINUE));
  24. }
  25. // 获取请求的uri
  26. String uri = req.uri();
  27. QueryStringDecoder decoder = new QueryStringDecoder(uri);
  28. if (!NO_LOG_URL.contains(decoder.path())) {
  29. log.info("请求路径:{},请求类型:{}", uri, req.method());
  30. }
  31. FullHttpResponse response = RequestControllerManager.getInstance().getRequestHandler(req.method().name(), decoder.path()).handle(req);
  32. if (!NO_LOG_URL.contains(decoder.path())) {
  33. log.info("响应内容:{}", response.content().toString(StandardCharsets.UTF_8));
  34. }
  35. ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
  36. }
  37. }