他对 HttpServletResponse.setHeader(...) 的使用可能用于包含 CRLF 字符

his use of HttpServletResponse.setHeader(...) might be used to include CRLF characters

我们在 java 代码中有以下语句:

    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

因此,findbugs 正在生成以下警告:

 [INFO] This use of HttpServletResponse.setHeader(...) might be used to include CRLF characters into HTTP headers HTTP_RESPONSE_SPLITTING

有什么方法可以修复这个警告吗?

以上问题已通过使用以下函数解决:

private String safeHttpHeader(String value) {
    String result = "";
    if (value != null) {
        char[] chars = value.toCharArray();
        StringBuilder buffer = new StringBuilder(chars.length);
        for (int i = 0; i < chars.length; i++) {
            switch (chars[i]) {
            case '\r':
                buffer.append('%');
                buffer.append('0');
                buffer.append('D');
                break;
            case '\n':
                buffer.append('%');
                buffer.append('0');
                buffer.append('A');
                break;
            default:
                buffer.append(chars[i]);
                break;
            }
        }
        result = buffer.toString();
    }
    return result;
}

声明

response.setHeader("Content-Disposition", safeHttpHeader("attachment; filename=\"" + dbFile.getFilename() + "\""));

希望对您有所帮助。

您可以使用 URI(String scheme, String ssp, String fragment) constructor to encode the file name then extract the raw Scheme-Specific part.

例如:

response.setHeader("Content-Disposition", "attachment; filename=\""
    + new URI("http", fileName, null).getRawSchemeSpecificPart() + "\"");

这是一个示例程序:

public static void main(String[] args) throws Exception {
    URI uri = new URI("http", "\r\n", null);
    System.out.println(uri.getRawSchemeSpecificPart());
}

将输出:

%0D%0A