proxyee icon indicating copy to clipboard operation
proxyee copied to clipboard

大佬,FullRequestIntercept里怎么才能直接返回数据

Open wolfing88 opened this issue 3 years ago • 1 comments

其他Intercept都有Channel,可以使用clientChannel.writeAndFlush(httpResponse);直接返回响应数据,但其他Intercept的httpRequest又获取不到请求参数,只有FullRequestIntercept里的FullHttpRequest才能获取到参数,不知道怎么才能获取到参数后直接响应数据

wolfing88 avatar Feb 15 '22 15:02 wolfing88

@wolfing88 下面再套一个拦截器就行了,示例代码:

public static void main(String[] args) throws Exception {
        HttpProxyServerConfig config = new HttpProxyServerConfig();
        config.setHandleSsl(true);
        new HttpProxyServer()
                .serverConfig(config)
                .proxyInterceptInitializer(new HttpProxyInterceptInitializer() {
                    @Override
                    public void init(HttpProxyInterceptPipeline pipeline) {
                        pipeline.addLast(new CertDownIntercept());
                        pipeline.addLast(new FullRequestIntercept() {

                            @Override
                            public boolean match(HttpRequest httpRequest, HttpProxyInterceptPipeline pipeline) {
                                //如果是json报文
                                if (HttpUtil.checkHeader(httpRequest.headers(), HttpHeaderNames.CONTENT_TYPE, "^(?i)application/json.*$")) {
                                    return true;
                                }
                                return false;
                            }

                        });
                        pipeline.addLast(new HttpProxyIntercept() {

                            @Override
                            public void beforeRequest(Channel clientChannel, HttpRequest httpRequest, HttpProxyInterceptPipeline pipeline) throws Exception {
                                if (httpRequest instanceof FullHttpRequest) {
                                    FullHttpRequest fullHttpRequest = (FullHttpRequest) httpRequest;
                                    ByteBuf content = fullHttpRequest.content();
                                    //打印请求信息
                                    System.out.println(fullHttpRequest.toString());
                                    System.out.println(content.toString(Charset.defaultCharset()));
                                    //修改响应
                                    FullHttpResponse fullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
                                    fullHttpResponse.content().writeBytes("test".getBytes());
                                    clientChannel.writeAndFlush(fullHttpResponse);
                                    return;
                                }
                                pipeline.beforeRequest(clientChannel, httpRequest);
                            }
                        });
                    }
                })
                .start(9999);
    }

monkeyWie avatar Feb 16 '22 03:02 monkeyWie