错误案例
现象描述:零批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; }