簡體   English   中英

如何在 Zuul 后置過濾器中攔截和編輯響應正文?

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

我正在使用 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.

任何人都可以幫我解決這個問題。

我遇到了同樣的錯誤,並且瘋狂地修改了如何在 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);
}

我有一個類似的任務,並試圖通過寫入 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);
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM