import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.HttpRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.embedded.netty.NettyReactiveWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.stereotype.Component;
import reactor.netty.ConnectionObserver;
import reactor.netty.NettyPipeline;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
@Component
@Slf4j
public class EncodeQueryNettyWebServerCustomizer implements WebServerFactoryCustomizer<NettyReactiveWebServerFactory> {
/**
* 需要encode的特殊字符
*/
private final List<Character> charList = new ArrayList<Character>() {
{
// this.add('{');
// this.add('}');
// this.add('[');
// this.add(']');
this.add('|');
}
};
@Override
public void customize(NettyReactiveWebServerFactory factory) {
factory.addServerCustomizers(httpServer -> httpServer.observe((conn, state) -> {
if (state == ConnectionObserver.State.CONNECTED) {
conn.channel().pipeline().addAfter(NettyPipeline.HttpCodec, "", new QueryHandler());
}
}));
}
class QueryHandler extends ChannelInboundHandlerAdapter {
QueryHandler() {
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws UnsupportedEncodingException {
if (msg instanceof HttpRequest) {
HttpRequest request = (HttpRequest) msg;
String url = request.uri();
// fix url
log.info("url: {}", url);
String[] split = url.split("\\?");
StringBuilder fixUrl = new StringBuilder(split[0]);
if (split.length > 1) {
fixUrl.append("?");
char[] chars = split[1].toCharArray();
for (char aChar : chars) {
if (charList.contains(aChar)) {
fixUrl.append(URLEncoder.encode(String.valueOf(aChar), "UTF-8"));
} else {
fixUrl.append(aChar);
}
}
}
log.info("fixUrl: {}", fixUrl);
request.setUri(fixUrl.toString());
}
ctx.fireChannelRead(msg);
}
}
}
版权属于:sunjianhua
本文链接:https://www.sunjianhua.cn/archives/spring-cloud-gateway-ignore-special-characters.html
转载时须注明出处及本声明,如果不小心侵犯了您的权益,请联系邮箱:NTA2MTkzNjQ1QHFxLmNvbQ==