数据流的读取

24 篇文章 0 订阅

错误案例

现象描述:零批II期中在对支付宝进行回调的过程中发现经常性的有支付宝返回数据解析不完整,经过检查发现如下错误代码:

InputStream is = postMethod.getResponseBodyAsStream();
byte[] bytes = new byte[4096];
is.read(bytes);
int count=0;
for(int i=0;i < bytes.length;i++){
   if(bytes[i]==0)
      break;
   count++;
   continue;
}

byte[] xmlBytes = new byte[count];
for(int i =0 ;i < xmlBytes.length; i++){
   xmlBytes[i] = bytes[i];
}
String xmlString = new String(xmlBytes,"GBK");

其中需要注意: byte[] bytes = new byte[4096];

错误分析

这里读取支付宝返回消息的时候设置了一个默认文件大小4096,但是超过这个大小后程序没有做好兼容的处理,不能保证4096能满足所有场景的使用,如果返回消息大小大于4096个字节,将会导致不能正确读取消息内容(部分消息内容丢失)。

正确用法

需要考虑到4096不够的情况,这里采用的是一个递归方法来读取返回的字节流:

private String getInputStr(InputStream in,String str) throws IOException{
  str = str==null? "" : str;
  byte[] b = new byte[4096];
  int cInt = -1;
  int index = 0;
  while((cInt = in.read()) != -1){
   b[index] = (byte)cInt;
   index++;
   if(index == ARR_BUFFER_SIZE){
    String xmlString = new String(b,"GBK");
    return getInputStr(in,str+xmlString);
   }
  }
  byte[] xmlBytes = new byte[index];
  System.arraycopy(b, 0, xmlBytes, 0, xmlBytes.length);
     String xmlString = new String(xmlBytes,"GBK");
     return str+xmlString;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值