实例如下所示 :
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 ("links", links); Karte <String, String> urlbyloanid = new HashMap <String, String> (); // map <string, string> urlbyloanid = zcmQueryInfoService.queryurlByLoanid (MAP); Versuchen Sie {if (urlbyloanid! // String wjurl = urlbyloanid.get ("url"); int i = wJurl.lastindexof ("/"); String Dateiname = wJurl.substring (i+1); URL URL = neue URL (WJURL); HttpurlConnection conn = (httpurlConnection) url.openconnection (); // 设置超时间为 3 秒 conn.setConnectTimeout (3*1000); // 防止屏蔽程序抓取而返回 403 错误 Conn.SetRequestProperty ("User-Agent", "Mozilla/4.0 (kompatibel; MSIE 5.0; Windows nt; Digext)"); // 得到输入流 InputStream InputStream = conn.getInputStream (); // 获取自己数组 byte [] bs = readInputStream (InputStream); Antwort.SetContentType ("Anwendung/Oktett-Stream; CharSet = ISO8859-1"); BufferedOutputStream output = null; BufferedInputStream input = null; try {output = new bufferedOutputStream (response.getOutputStream ()); // 中文文件名必须转码为 ISO8859-1, 否则为乱码 String fileNamedown = new String (Dateiname.getBytes (), "ISO8859-1"); // 作为附件下载 response.setheader ("Inhaltsdisposition", "Anhang; Dateiname =" + FileNamedown); output.write (bs); Antwort.FlushBuffer (); } catch (Ausnahme e) {log.Error ("Log -Dateifehler herunterladen", e); } // 用户可能取消了下载 endlich {if (input! = Null) try {input.close (); } catch (ioException e) {e.printstacktrace (); } if (output! = null) try {output.close (); } catch (ioException e) {e.printstacktrace (); }}}} catch (Ausnahme e) {e.printstacktrace (); }}/ ** * 从输入流中获取字节数组 * @param InputStream * @return * @throws ioException */ public static byte [] readInputStream (InputStream InputStream) löst ioException {byte [] buffer = new byte [1024] aus; int len = 0; BytearrayoutputStream bos = new bytearrayoutputStream (); while ((len = inputStream.read (puffer))! = -1) {bos.write (puffer, 0, len); } bos.close (); return bos.tobytearray (); }以上这篇 Java 通过 url 下载文件并输出的方法就是小编分享给大家的全部内容了 , 希望能给大家一个参考 , 也希望大家多多支持武林网。 也希望大家多多支持武林网。 也希望大家多多支持武林网。