错误:Parse Error: Invalid header value char(已解决)
前言
将压缩包写入响应流时报的错。
错误代码
String zipName = "压缩包.zip";
try {
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment;filename=" + zipName); // 报错
response.getOutputStream().write(zipStream.toByteArray());
} finally {
zipStream.close();
}
原因分析
- 这个错误通常是由于
zipName
中包含了无效的字符导致的。 - 错误发生在设置响应头(response header)时,具体是在设置
Content-Disposition
头的值时出错。 - HTTP 头的值应该是有效的 ASCII 字符,并且不能包含特殊字符或非 ASCII 字符。根据错误信息,
zipName
中可能包含了一个或多个无效字符,导致无法设置正确的头值。
解决方法
对 zipName
进行编码,确保其中的特殊字符被正确处理。你可以使用 URLEncoder
对文件名进行编码,如下所示:
String zipName = "压缩包.zip";
zipName = URLEncoder.encode(zipName, "UTF-8"); // 主要添加这行代码
try {
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment;filename=" + zipName);
response.getOutputStream().write(zipStream.toByteArray());
} finally {
zipStream.close();
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/189747.html