java通过url下载文件并输出的方法
实例如下所示:
controller:
@RequestMapping(value="/{loanid}/{atmtType}")
publicvoiddoGet(@PathVariable("loanid")Stringloanid,@PathVariable("atmtType")StringatmtType,
HttpServletRequestreq,HttpServletResponseresponse){
Mapmap=newHashMap();
map.put("loanid",loanid);
MapurlByLoanid=newHashMap();
//MapurlByLoanid=zcmQueryInfoService.queryUrlByLoanid(map);
try{
if(urlByLoanid!=null){
Stringwjurl="http://10.0.15.11:8080/gateway//nfs/marvel-core-admin/2017/10/11/compact_seal_17101119371231615_7.pdf";
//Stringwjurl=urlByLoanid.get("url");
inti=wjurl.lastIndexOf("/");
StringfileName=wjurl.substring(i+1);
URLurl=newURL(wjurl);
HttpURLConnectionconn=(HttpURLConnection)url.openConnection();
//设置超时间为3秒
conn.setConnectTimeout(3*1000);
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent","Mozilla/4.0(compatible;MSIE5.0;WindowsNT;DigExt)");
//得到输入流
InputStreaminputStream=conn.getInputStream();
//获取自己数组
byte[]bs=readInputStream(inputStream);
response.setContentType("application/octet-stream;charset=ISO8859-1");
BufferedOutputStreamoutput=null;
BufferedInputStreaminput=null;
try{
output=newBufferedOutputStream(response.getOutputStream());
//中文文件名必须转码为ISO8859-1,否则为乱码
StringfileNameDown=newString(fileName.getBytes(),"ISO8859-1");
//作为附件下载
response.setHeader("Content-Disposition","attachment;filename="+fileNameDown);
output.write(bs);
response.flushBuffer();
}catch(Exceptione){
log.error("Downloadlogfileerror",e);
}//用户可能取消了下载
finally{
if(input!=null)
try{
input.close();
}catch(IOExceptione){
e.printStackTrace();
}
if(output!=null)
try{
output.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
}catch(Exceptione){
e.printStackTrace();
}
}
/**
*从输入流中获取字节数组
*@paraminputStream
*@return
*@throwsIOException
*/
publicstaticbyte[]readInputStream(InputStreaminputStream)throwsIOException{
byte[]buffer=newbyte[1024];
intlen=0;
ByteArrayOutputStreambos=newByteArrayOutputStream();
while((len=inputStream.read(buffer))!=-1){
bos.write(buffer,0,len);
}
bos.close();
returnbos.toByteArray();
}     
以上这篇java通过url下载文件并输出的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。
