我正在尝试在REST api中实现内容摘要标头。当我为我的回复创建摘要时,它总是省略最后一个字符。
public class ContentDigestFilter扩展OncePerRequestFilter {
@Override
protected boolean shouldNotFilterAsyncDispatch() {
return false;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
HttpServletResponse responseToUse = response;
if (!isAsyncDispatch(request) && !(response instanceof ContentCachingResponseWrapper)) {
responseToUse = new HttpStreamingAwareContentCachingResponseWrapper(response, request);
}
filterChain.doFilter(request, responseToUse);
updateResponse(request, responseToUse);
}
private void updateResponse(HttpServletRequest request, HttpServletResponse response) throws IOException {
ContentCachingResponseWrapper responseWrapper =
WebUtils.getNativeResponse(response, ContentCachingResponseWrapper.class);
Assert.notNull(responseWrapper, "ContentCachingResponseWrapper not found");
HttpServletResponse rawResponse = (HttpServletResponse) responseWrapper.getResponse();
int statusCode = responseWrapper.getStatusCode();
if (rawResponse.isCommitted()) {
responseWrapper.copyBodyToResponse();
}
else{
String digest = getContentDigest(responseWrapper.getContentInputStream());
rawResponse.setHeader("X-Digest",digest);
responseWrapper.copyBodyToResponse();
}
}
protected String getContentDigest(InputStream inputStream) throws IOException {
try {
byte[] dataArray = StreamUtils.copyToByteArray(inputStream);
//dataArray doesn't include last character of response body.
System.out.println("Response Body: " + new String(dataArray,"UTF-8"));
String digest = ""; //Generate digest with HMAC-SHA512
return digest;
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return "NoDigest";
}
private static class HttpStreamingAwareContentCachingResponseWrapper extends ContentCachingResponseWrapper {
private final HttpServletRequest request;
public HttpStreamingAwareContentCachingResponseWrapper(HttpServletResponse response, HttpServletRequest request) {
super(response);
this.request = request;
}
@Override
public ServletOutputStream getOutputStream() throws IOException {
return super.getOutputStream();
}
@Override
public PrintWriter getWriter() throws IOException {
return super.getWriter();
}
}
}
在方法getContentDigest中,如果我打印dataArray,它不包含响应的最后一个字符