问题:java 通过http请求并且返回流数据,使用两次报错。
原因:httpclient的获取实体流只能使用一次,不能重复使用。
解决办法:
方案一:
进行两次请求。
代码不举例子。
方案二:
首先保存流数据,再通过流 reset方法重置游标。
代码:
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();