java.lang.IllegalStateException: Cannot call sendError() after the response has

异常出现的场景:

(1)ssh项目,提供下载功能。项目使用tomcat部署;

(2)写了一个测试类来测试下载功能,执行时报异常:

Java.lang.IllegalStateException: Cannot call sendError() after the response has been committed

 

下载类在struts中的配置(截取):

Xml代码   收藏代码
  1. <action name="downloadOneFile" class="downloadOneFileAction">  
  2.             <result type="stream" name="success">  
  3.                 <param name="inputName">downloadFile</param>  
  4.                 <param name="contentType"></param>  
  5.                 <param name="contentDisposition">attachment;filename=${filename}</param>  
  6.                 <param name="bufferSize">4096</param>  
  7.             </result>  
  8.         </action>  

在测试代码中使用 HttpURLConnection模拟浏览器发送http请求,读取应答体的部分代码如下:



上述代码是有问题的,本来bis中有1k的字节,结果我试图读取2k的字节,所以就报错了,原因找到了,怎么解决呢?

修改为:

Java代码   收藏代码
  1. private static byte[] readDataFromLength2(HttpURLConnection huc,  
  2.             int contentLength) throws Exception {  
  3.   
  4.         InputStream in = huc.getInputStream();  
  5.         BufferedInputStream bis = new BufferedInputStream(in);  
  6.   
  7.         // 数据字节数组  
  8.         byte[] receData = new byte[contentLength];  
  9.         int readLength = 0;  
  10.         // 数据数组偏移量  
  11.         int offset = 0;  
  12.   
  13.         readLength = bis.read(receData, offset, contentLength);  
  14.         // 已读取的长度  
  15.         int readAlreadyLength = readLength;  
  16.         while (readAlreadyLength < contentLength) {  
  17.             readLength = bis.read(receData, readAlreadyLength, contentLength  
  18.                     - readAlreadyLength);  
  19.             readAlreadyLength = readAlreadyLength + readLength;  
  20.         }  
  21.       
  22.         return receData;  
  23.     }  

 解决问题的过程:

1刚开始以为是编码的问题,怀疑BufferedInputStream bis = new

BufferedInputStream(in);BufferedInputStream的构造方法的第二个参数是编码(如GBK,UTF-8等),结果证明没有这个参数;

2bis.read的第三个参数刚开始以为是索引,结果发现是长度(读取的字节);

3while中比较时,应该是readAlreadyLengthcontentLength进行比较。 

参阅附件中com.http.util.HttpSocketUtil  .附件中的项目是使用maven 构建的。

注意读取BufferedInputStream时 使用while循环是必要的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值