Netty Socket 端口如何禁止 HTTP 请求
可以使用 Netty 提供的 HttpServerCodec 来拦截 HTTP 请求,然后直接关闭连接。具体实现可以参考以下代码:
- 创建一个
ChannelInitializer来设置 pipeline:
public class MyChannelInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new HttpServerCodec());
pipeline.addLast(new HttpHandler());
}
}
- 创建一个
HttpHandler来处理 HTTP 请求:
public class HttpHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
if (msg.decoderResult().isFailure()) {
sendErrorResponse(ctx.channel(), HttpResponseStatus.BAD_REQUEST);
return;
}
if (msg.method() == HttpMethod.GET) {
// 允许 GET 请求
ctx.fireChannelRead(msg);
} else {
// 禁止其他 HTTP 请求
sendErrorResponse(ctx.channel(), HttpResponseStatus.FORBIDDEN);
ctx.close();
}
}
private void sendErrorResponse(Channel channel, HttpResponseStatus status) {
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status);
response.headers().set(HttpHeaderNames.CONTENT_TYPE, 'text/plain; charset=UTF-8');
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
channel.writeAndFlush(response);
}
}
上述代码中,我们首先使用 HttpServerCodec 来解析 HTTP 请求。然后在 HttpHandler 中,我们判断请求方法是否为 GET,如果是则继续处理,否则直接关闭连接并返回 403 Forbidden 响应。这样就可以禁止除 GET 外的其他 HTTP 请求了。
原文地址: https://www.cveoy.top/t/topic/m8zz 著作权归作者所有。请勿转载和采集!