前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Attempted read from closed stream 问题以及解决方案

Attempted read from closed stream 问题以及解决方案

作者头像
斯文的程序
发布2019-11-07 18:56:43
5.5K1
发布2019-11-07 18:56:43
举报
文章被收录于专栏:带你回家

问题:java 通过http请求并且返回流数据,使用两次报错。

原因:httpclient的获取实体流只能使用一次,不能重复使用。

解决办法:

方案一:

进行两次请求。

代码不举例子。

方案二:

首先保存流数据,再通过流 reset方法重置游标。

代码:

代码语言:javascript
复制
  DefaultHttpClient httpClient = new DefaultHttpClient();
		        HttpPost httpPost = new HttpPost(url);
		        httpPost.setEntity(new UrlEncodedFormEntity(paramList, Consts.UTF_8));
		        HttpResponse response = httpClient.execute(httpPost);
		        HttpEntity entity = response.getEntity();
		        
		        InputStream in = entity.getContent();//获取数据流
	         
		        // 保存流
		        ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
		        BufferedInputStream br = new BufferedInputStream(in); 
		        byte[] b = new byte[1024]; 
		        for (int c = 0; (c = br.read(b)) != -1;) 
		        { 
		            bos.write(b, 0, c); 
		        } 
		        b = null; 
		        br.close(); 
		        
		        
		        in = new ByteArrayInputStream(bos.toByteArray());
		        // 第一次读流
		        StringBuffer out = new StringBuffer();
		        byte[] b1 = new byte[1024]; 
		        for (int n; (n = in.read(b1)) != -1;) {
		             out.append(new String(b1, 0, n));  //这个可以用来读取文件内容 并且文件内容有中文读取出来也不会乱码
		        }
		        // 判断文件是否存在
		        String resultHtml = out.toString();
		        int firstIndex = resultHtml.indexOf("\n");
		        if(firstIndex < 0){
		        	logger.info("文件不存在或异常"+resultHtml);
		        	return false;
		        }
		        // 重置游标
		        in.reset();
		        
		        // 输出到文件
        	    FileOutputStream fos = new FileOutputStream(new File(req.getFilePath()));
                BufferedOutputStream  bos1 = new BufferedOutputStream(fos,2048);
              	// 第二次读流
              	int len;
	   		    byte [] bytes = new byte[2048];
	   		    while((len=in.read(bytes,0,2048)) != -1){
	   		    	bos1.write(bytes,0,len);
	   		    }
	   		    bos1.flush();
		        bos1.close();
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档