为了解决Netty解码http请求获取URL乱码问题,我们需要:
- 设置正确的字符集
在Netty中解析http请求时,如果没有指定字符集,Netty默认使用ISO-8859-1字符集进行解析。此时如果请求URL中含有中文等非ASCII字符,就会出现乱码问题。因此我们需要手动设置正确的字符集。
设置字符集的方法很简单,只需要在ChannelPipeline中添加一个ChannelInitializer,重写其initChannel方法,在其中添加一个HttpRequestDecoder并指定字符集即可,示例代码如下:
public class HttpServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new HttpRequestDecoder(Charset.forName("UTF-8")));
pipeline.addLast(new HttpServerHandler());
}
}
- UrlDecoder解码
在网路传输过程中,URL被转码压缩,这个过程叫做URL编码。URL编码的结果是原始URL的一个字符串映射。URLDecoder类能够对这种映射进行反编码,还原出原始URL。因此我们需要在Netty中解码URL,示例代码如下:
public class HttpServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof FullHttpRequest) {
FullHttpRequest request = (FullHttpRequest) msg;
// 反编码URL
String uri = URLDecoder.decode(request.uri(), "UTF-8");
// 打印反编码后的URL
System.out.println("Received URI: " + uri);
// 处理请求
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
response.content().writeBytes("Response body".getBytes());
ctx.writeAndFlush(response);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
至此,我们已经解决了Netty解码http请求获取URL乱码问题。
示例1:
客户端发送的请求:
GET /%E4%B8%AD%E6%96%87 HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9
服务端打印的请求URI为:
Received URI: /中文
示例2:
客户端发送的请求:
GET /example/test%20abc HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9
服务端打印的请求URI为:
Received URI: /example/test abc
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:解决Netty解码http请求获取URL乱码问题 - Python技术站