Java 实现的断点下载
发布时间:2020-12-15 03:19:27 所属栏目:Java 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 HttpServletRequest / Response HttpClient ServletOutputStream BufferedInputStream /** * @desc 断点下载工具方法 * @param request * @param resp
以下代码由PHP站长网 52php.cn收集自互联网 现在PHP站长网小编把它分享给大家,仅供参考
/** * @desc 断点下载工具方法 * @param request * @param response * @param fileLength * @param contentType * @param fileName * @param fileId */ public static void resumeDownload(HttpServletRequest request,HttpServletResponse response,Long fileLength,String contentType,String fileName,String fileId) { ServletOutputStream out = null; response.reset(); // 记录断点续传的开始点 long pos = 0; if (null != request.getHeader("Range")) { response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); try { pos = Long.parseLong(request.getHeader("Range") .replaceAll("bytes=","").replaceAll("-.*","")); } catch (NumberFormatException e) { LOGGER.error(e.getMessage(),e); pos = 0; } String contentRange = new StringBuffer("bytes ").append(pos + "") .append("-").append((fileLength.intValue() - 1) + "") .append("/").append(fileLength.intValue() + "").toString(); response.setHeader("Content-Range",contentRange); } response.setHeader("Accept-Ranges","bytes"); response.setHeader("Content-Length",String.valueOf(fileLength.intValue() - pos)); response.setCharacterEncoding("UTF-8"); response.setContentType(contentType); response.setHeader("Content-disposition","attachment;filename="" + fileName + """); try { out = response.getOutputStream(); } catch (IOException e) { LOGGER.error(e.getMessage(),e); } // 断点下载 CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(SysConf.getString("fezo.download.url")); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair(SysConf.getString("fezo.download.param"),fileId)); HttpResponse httpResponse = null; BufferedInputStream input = null; try { httpPost.setEntity(new UrlEncodedFormEntity(nvps)); httpPost.setHeader("Range","bytes=" + pos + "-"); httpResponse = httpClient.execute(httpPost); input = new BufferedInputStream(httpResponse.getEntity().getContent()); byte[] buffer = new byte[CommonConstants.BUFFER_SIZE]; int len = -1; while ((len = input.read(buffer)) != -1) { out.write(buffer,len); } out.flush(); out.close(); input.close(); } catch (UnsupportedEncodingException e) { LOGGER.error(e.getMessage(),e); } catch (ClientProtocolException e) { LOGGER.error(e.getMessage(),e); } catch (IOException e) { // 可以忽略这个异常,有可能是用户暂停下载,或者迅雷等下载工具分块下载 } finally { try { if (httpClient != null) httpClient.close(); } catch(IOException e) { LOGGER.error(e.getMessage(),e); } } } >>>点击这里下载代码 4. 重点与难点 ??? - 迅雷等多线程分块下载客户端下载的处理:还是要处理好"Range" 和 "Conent-Range" 等头部信息,迅雷会自动将文件内容分块、记录起始位置。 来自:http://blog.csdn.net/alli0968/article/details/47337349 以上内容由PHP站长网【52php.cn】收集整理供大家参考研究 如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |