我们在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
有没有办法解决这个警告?
答案 0 :(得分:0)
使用以下功能解决了上述问题:
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() + "\""));
希望它有所帮助。
答案 1 :(得分:0)
您可以使用URI(String scheme, String ssp, String fragment)构造函数对文件名进行编码,然后提取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