当前位置: 移动技术网 > IT编程>开发语言>Java > java通过url下载文件并输出的方法

java通过url下载文件并输出的方法

2019年07月19日  | 移动技术网IT编程  | 我要评论

实例如下所示:

controller:
@requestmapping(value = "/{loanid}/{atmttype}")
 public void doget(@pathvariable("loanid") string loanid,@pathvariable("atmttype") string atmttype,
   httpservletrequest req,httpservletresponse response) {
  map<string,string> map = new hashmap<string,string>();
  map.put("loanid", loanid);
  map<string, string> urlbyloanid= new hashmap<string,string>();
 // map<string, string> urlbyloanid = zcmqueryinfoservice.queryurlbyloanid(map);
  try {
   if(urlbyloanid!=null){
    string wjurl="http://10.0.15.11:8080/gateway//nfs/marvel-core-admin/2017/10/11/compact_seal_17101119371231615_7.pdf";
    //string wjurl = urlbyloanid.get("url");
    int i = wjurl.lastindexof("/");
    string filename = wjurl.substring(i+1);
    
    url url = new url(wjurl); 
    httpurlconnection conn = (httpurlconnection)url.openconnection(); 
    //设置超时间为3秒 
    conn.setconnecttimeout(3*1000); 
    //防止屏蔽程序抓取而返回403错误 
    conn.setrequestproperty("user-agent", "mozilla/4.0 (compatible; msie 5.0; windows nt; digext)"); 
    //得到输入流 
    inputstream inputstream = conn.getinputstream(); 
    //获取自己数组 
    byte[] bs = readinputstream(inputstream); 
    response.setcontenttype("application/octet-stream;charset=iso8859-1");
    bufferedoutputstream output = null;
    bufferedinputstream input = null;
     try {
      output = new bufferedoutputstream(response.getoutputstream());
      // 中文文件名必须转码为 iso8859-1,否则为乱码
      string filenamedown = new string(filename.getbytes(), "iso8859-1");
      // 作为附件下载
      response.setheader("content-disposition", "attachment;filename=" + filenamedown);
  
      output.write(bs);
      response.flushbuffer();
     } catch (exception e) {
      log.error("download log file error", e);
     } // 用户可能取消了下载
     finally {
      if (input != null)
       try {
        input.close();
       } catch (ioexception e) {
        e.printstacktrace();
       }
      if (output != null)
       try {
        output.close();
       } catch (ioexception e) {
        e.printstacktrace();
       }
     }
   }
  } catch (exception e) {
   e.printstacktrace();
  }
 }
/** 
  * 从输入流中获取字节数组 
  * @param inputstream 
  * @return 
  * @throws ioexception 
  */ 
 public static byte[] readinputstream(inputstream inputstream) throws ioexception { 
  byte[] buffer = new byte[1024]; 
  int len = 0; 
  bytearrayoutputstream bos = new bytearrayoutputstream(); 
  while((len = inputstream.read(buffer)) != -1) { 
   bos.write(buffer, 0, len); 
  } 
  bos.close(); 
  return bos.tobytearray(); 
 } 

以上这篇java通过url下载文件并输出的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网