如何在 Zuul post 过滤器中拦截和编辑响应主体?

How to intercept and edit response body in Zuul post filter?

我正在使用 Zuul post 过滤器来拦截响应。我的要求是向响应 json 添加一个新字段。我能够拦截响应并对其进行编辑。但是,无法将更新的响应设置为 RequestContext.How 在 post 过滤器中使用 Zuul 作为代理时,可以读取响应主体,编辑并将其更新回 RequestContext?

请找到我正在使用的以下代码。

private void updateResponseBody(RequestContext ctx) throws IOException, JSONException {

    final InputStream responseDataStream = ctx.getResponseDataStream();
    String responseData = CharStreams.toString(new InputStreamReader(responseDataStream, "UTF-8"));
    JSONObject jsonObj = new JSONObject(responseData);
    JSONArray groupsArray = jsonObj.getJSONArray("list");
    for (int i = 0; i < groupsArray.length(); i++) {
        JSONObject groupId = groupsArray.getJSONObject(i);
        groupId.accumulate("new_json_field_name", "new_json_field_value");
    }
    String updatedResponse = jsonObj.toString();
    // ctx.setResponseBody(body); // also not working
    ctx.setResponseDataStream(org.apache.commons.io.IOUtils.toInputStream(updatedResponse, "UTF-8"));

}

我得到的错误是:

Error while sending response to client: java.io.IOException: An existing connection was forcibly closed by the remote host.

谁能帮我解决这个问题。

我遇到了同样的错误,疯狂地修改了 trying different possibilities. Finally I found the solution in this post 中描述的代码,将答案写在 servletResponse.getOutputStream()OutputStream 而不是 ctx.setResponseDataStream():

HttpServletResponse servletResponse = ctx.getResponse();

  ...

String updatedResponse = jsonObj.toString();
try {
    OutputStream outStream = servletResponse.getOutputStream();
    outStream.write(updatedResponse.getBytes(), 0, updatedResponse.length());
    outStream.flush();
    outStream.close();
} catch (IOException e) {
    log.warn("Error reading body", e);
}

我有一个类似的任务,并尝试通过写入 OutputStream 来完成。这有效,但有一个 st运行ge 副作用,它使响应中的 HttpHeaders 被删除或损坏。这使得调用在生产中产生 CORS 错误,即使它 运行 在本地通过 Postman 正常。

我编写了以下方法,我从 Post Zuul Filter 的 运行() 方法中调用,以将单个 node/value 添加到 return Json.

    private void addJsonNode(RequestContext requestContext,String name, String id) {
        HttpServletResponse servletResponse = requestContext.getResponse();
        try {
            final InputStream responseDataStream = requestContext.getResponseDataStream();
            String responseData = CharStreams.toString(new InputStreamReader(responseDataStream, "UTF-8"));
            JSONObject jsonObject = new JSONObject(responseData);
            jsonObject.put(name, id);
            String updatedResponse = jsonObject.toString(4);
            requestContext.setResponseBody(updatedResponse);
        } catch (IOException e) {
            log.warn("Error reading body", e);
        } catch (JSONException e) {
            log.warn("Error reading body", e);
        }
    }