gpt4 book ai didi

java - 如何在Zuul后置过滤器中拦截和编辑响应体?

转载 作者:行者123 更新时间:2023-12-02 04:01:10 24 4
gpt4 key购买 nike

我正在使用 Zuul 后置过滤器来拦截响应。我的要求是向响应 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.

任何人都可以帮我解决这个问题吗?

最佳答案

我遇到了同样的错误,并疯狂地修改How to get response body in Zuul post filter?中描述的代码尝试不同的可能性。最后我在this post中找到了解决方案通过在 servletResponse.getOutputStream() 而不是 ctx.setResponseDataStream()OutputStream 中写入答案:

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);
}

关于java - 如何在Zuul后置过滤器中拦截和编辑响应体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56733426/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com