HttpServletResponse设置headers返回,发现headers中缺少“Content-Length“和“Content-Type“两个参数。

业务中需要将用httpUtils请求返回的headers全部返回,塞到HttpServletResponse中,代码如下:

HttpServletResponse response;

// 返回headers
Arrays.stream(httpResponse.getHeaders()).forEach(header -> response.setHeader(header.getName(), header.getValue()));

一、发现问题:

塞到HttpServletResponse中之后,发现headers中缺少"Content-Length"和"Content-Type"两个参数。

使用http直接请求,和使用本项目代理请求对比,发现最后headers中缺少"Content-Length"和"Content-Type"。

二、查找问题

看源码发现遇到这两个特殊字段时,分别赛到了setContentTypesetContentLength

三、解决问题

所以需要再遍历时候重新赛回去

for (Header header : httpResponse.getHeaders()) {
        if ("Content-Type".equalsIgnoreCase(header.getName())) {
            response.setContentType(header.getValue());
        } else if ("Content-Length".equalsIgnoreCase(header.getName())) {
            response.setContentLength(Integer.valueOf(header.getValue()));
        } else {
            response.setHeader(header.getName(), header.getValue());
        }
}

  • 10
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
@RequestMapping(value = "export", method = RequestMethod.GET) public void exportToExcel(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException { System.out.println("111"); List<Attendance> attendanceList = (List<Attendance>) session.getAttribute("list"); // 创建 Excel 文档 Workbook workbook = new XSSFWorkbook(); Sheet sheet = workbook.createSheet("Attendance"); // 创建表头 Row headerRow = sheet.createRow(0); String[] headers = {"考勤ID", "用户ID", "用户名", "考勤时间", "考勤类型"}; for (int i = 0; i < headers.length; i++) { Cell cell = headerRow.createCell(i); cell.setCellValue(headers[i]); } // 填充数据 int rowIndex = 1; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); for (Attendance attendance : attendanceList) { Row dataRow = sheet.createRow(rowIndex); dataRow.createCell(0).setCellValue(attendance.getAttendanceid()); dataRow.createCell(1).setCellValue(attendance.getUserid()); dataRow.createCell(2).setCellValue(attendance.getUsername()); dataRow.createCell(3).setCellValue(sdf.format(attendance.getDate())); dataRow.createCell(4).setCellValue(attendance.getType()); rowIndex++; } // 设置响应头 response.setHeader("content-type", "application/octet-stream"); response.setContentType("application/force-download"); response.addHeader("Content-Disposition", "attachment; filename=attendance.xlsx"); // 将 Excel 数据写入响应输出流 OutputStream outputStream = response.getOutputStream(); workbook.write(outputStream); workbook.close(); outputStream.flush(); outputStream.close(); }
06-12
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值