如何在 Zuul 帖子过滤器中拦截和编辑响应正文?



我正在使用 Zuul post filter 来拦截响应。我的要求是向响应 json 添加一个新字段。我能够拦截响应并对其进行编辑。但是,无法将更新的响应设置为RequestContext.如何在使用Zuul作为post过滤器中的代理时读取响应正文,编辑并将其更新回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.

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

我遇到了同样的错误,并且疯狂地修改了如何在 Zuul 后过滤器中获取响应正文中描述的代码? 尝试不同的可能性。最后,我在这篇文章中找到了解决方案,方法是在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);
}

我有一个类似的任务,并试图通过写入输出流来完成。这奏效了,但有一个奇怪的副作用,它使响应中的 HttpHeader 被删除或损坏。这使得调用在生产中产生 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);
}
}

最新更新