Spring Cloud Gateway -- ResponseBody修改(解决ResponseBody不完整的问题)

前言

由于对方接口传输数据可能是xml,可能是json的,但是我希望前端获取到的响应是json格式的,所以需要在在响应中修改一下。

Response修改

由于接口返回数据较多,采用 fluxBody.map(dataBuffer -> 这个方式获取数据是不完整的。其实是多次调用了这个方法。

				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"));
                        //TODO,s就是response的值,想修改、查看就随意而为了
                        byte[] uppedContent = new String(content, Charset.forName("UTF-8")).getBytes();
                        return bufferFactory.wrap(uppedContent);
                    }));

采用循环调用之后 再将内容拼接好就能获取到完整的ResponseBody。
这里有一个小问题由于不知道修改完的Body长度,只能采用了分块编码这种代替了CONTENT_LENGTH。
尝试了一下好像是触发getHeaders()这个方法,再执行writeWith()这个方法。导致了计算不出来CONTENT_LENGTH。
(不知道有没有人能解决这个问题)

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse originalResponse = exchange.getResponse();
        // 定义新的消息头
        HttpHeaders headers = new HttpHeaders();
        headers.putAll(exchange.getResponse().getHeaders());

        ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
            @Override
            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                if (getStatusCode().equals(HttpStatus.OK) && body instanceof Flux) {
                    Flux<? extends DataBuffer> fluxBody = Flux.from(body);
                    return super.writeWith(fluxBody.buffer().map(dataBuffers -> {
                        List<String> list = new ArrayList<String>();
                        dataBuffers.forEach(dataBuffer -> {
                            byte[] content = new byte[dataBuffer.readableByteCount()];
                            dataBuffer.read(content);
                            DataBufferUtils.release(dataBuffer);
                            try {
                                list.add(new String(content, "utf-8"));
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        });
                        String s = listToString(list);
                        if(isXML(s)){
                            Map m = json2map(xml2jsonString(s,"").get("data").toString(),"");
                            s = map2Json(m);
                        }
                        int length = s.getBytes().length;
                        headers.setContentLength(length);
                        return bufferFactory().wrap(s.getBytes());
                    }));
                }
                return super.writeWith(body);
            };
            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders httpHeaders = new HttpHeaders();
                httpHeaders.putAll(super.getHeaders());
                //由于修改了请求体的body,导致content-length长度不确定,因此使用分块编码
                httpHeaders.remove(HttpHeaders.CONTENT_LENGTH);
                httpHeaders.set(HttpHeaders.TRANSFER_ENCODING, "chunked");
                return httpHeaders;
            }
        };

        // replace response with decorator
        return chain.filter(exchange.mutate().response(decoratedResponse).build());
    }

Logo

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

更多推荐