在网上找到了一篇关于gateway获取响应数据的代码,自己加了了一下代码 如下`

import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
 
import java.nio.charset.Charset;
 

@Component
public class WrapperResponseGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public int getOrder() {
        return -2;
    }
 
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse originalResponse = exchange.getResponse();
        DataBufferFactory bufferFactory = originalResponse.bufferFactory();
        ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
            @Override
            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                if (body instanceof Flux) {
                    Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;
                    return super.writeWith(fluxBody.map(dataBuffer -> {
                        // probably should reuse buffers
                        byte[] content = new byte[dataBuffer.readableByteCount()];
                        dataBuffer.read(content);
                        //释放掉内存
                        DataBufferUtils.release(dataBuffer);
                        String s = new String(content, Charset.forName("UTF-8"));
                        JSONObject respondseObject = JSONUtil.parseObj(s);
                        String status = String.valueOf(respondseObject.get("status"));
                        logger.info("接口状态: {}", status);
                        //TODO,s就是response的值,想修改、查看就随意而为了
                        byte[] uppedContent = new String(content, Charset.forName("UTF-8")).getBytes();
                        return bufferFactory.wrap(uppedContent);
                    }));
                }
                // if body is not a flux. never got there.
                return super.writeWith(body);
            }
        };
        // replace response with decorator
        return chain.filter(exchange.mutate().response(decoratedResponse).build());
    }
}

用postman测试接口,返回的数据是正常的,但是浏览器访问接口时却报错了,debug后问题就出在 String s = new String(content, Charset.forName(“UTF-8”)); 因为postman请求是转换的数据是完整的,但是浏览器访问接口时,转换出的数据缺失了,以至于 JSONObject respondseObject = JSONUtil.parseObj(s); 报错cn.hutool.json.JSONException: Unterminated string at 604 [character 605 line 1]

经过上网查阅终于解决了

修改上述代码 如下

ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
            @Override
            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                if (body instanceof Flux) {
                    Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;
                    return super.writeWith(fluxBody.buffer().map(dataBuffer -> {
//                            HttpStatus statusCode = exchange.getResponse().getStatusCode();
                        // probably should reuse buffers
                        DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
                        DataBuffer buffer= dataBufferFactory.join(dataBuffer);

                        byte[] content = new byte[buffer.readableByteCount()];
                        buffer.read(content);
                        //释放掉内存
                        DataBufferUtils.release(buffer);
                        String s = new String(content, Charset.forName("UTF-8"));

                        JSONObject respondseObject = JSONUtil.parseObj(s);
                        String status = String.valueOf(respondseObject.get("status"));
                        logger.info("接口状态: {}", status);
                        //TODO,s就是response的值,想修改、查看就随意而为了
                        byte[] uppedContent = s.getBytes();
                        return bufferFactory.wrap(uppedContent);
                    }));
                }
                // if body is not a flux. never got there.
                return super.writeWith(body);
            }
        };

DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
DataBufferFactory可以一次性join完所有数据, 所以就不会出现数据缺失问题

问题解决!

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐