为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 Zuul post filter 中拦截和编辑响应体?

如何在 Zuul post filter 中拦截和编辑响应体?

千万里不及你 2023-02-16 17:19:16
我正在使用 Zuul post filter 来拦截响应。我的要求是向响应 json 添加一个新字段。我能够拦截响应并对其进行编辑。但是,无法将更新后的响应设置为 RequestContext。在后过滤器中使用 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.谁能帮我解决这个问题。
查看完整描述

2 回答

?
蓝山帝景

TA贡献1843条经验 获得超7个赞

我遇到了同样的错误,疯狂地修改了How to get response body in Zuul post filter? 中描述的代码。尝试不同的可能性。最后,我在这篇文章中找到了解决方案,方法是在OutputStreamfromservletResponse.getOutputStream()而不是 中写下答案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);

}


查看完整回答
反对 回复 2023-02-16
?
泛舟湖上清波郎朗

TA贡献1818条经验 获得超3个赞

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


我编写了以下方法,我从我的 Post Zuul 过滤器的 run() 方法调用该方法以将单个节点/值添加到返回的 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);

        }

    }


查看完整回答
反对 回复 2023-02-16
  • 2 回答
  • 0 关注
  • 89 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信