org.apache.http.client.HttpClient 访问服务器限速下载文件
2017-01-05 14:18
627 查看
org.apache.http.client.HttpClient 访问服务器限速下载文件
前端代码:public static boolean doOutputStreamDownload(String fileName,String localPath,String remotePath) throws Exception{ logger.info("doOutputStreamDownload( downloadPath : "+remotePath+", localPath : "+localPath+" , fileName : "+fileName+" )"); if (StringUtil.isEmpty(remotePath)||StringUtil.isEmpty(localPath)||StringUtil.isEmpty(fileName)) { logger.error("getPackageOutputStream the parm is invalid!"); return false; } UpdateToolRequestBean request=new UpdateToolRequestBean(); request.setDownloadPath(remotePath+"/"+fileName); long downloadSpreed; try { downloadSpreed=Long.parseLong(SPREED); } catch (Exception e) { // TODO: handle exception logger.error("download spreed parse long exception ,set spreed=-1. ( "+e+" )"); downloadSpreed=-1; } request.setSpreed(downloadSpreed); ObjectMapper objectMapper = JacksonHelper.objectMapper(); String requestJsonStr = objectMapper.writeValueAsString(request); HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 20 * 1000); org.apache.http.client.HttpClient httpclient = new DefaultHttpClient(httpParams); logger.info("http post url is "+URL); HttpPost httppost = new HttpPost(URL); List<NameValuePair> formParams = new LinkedList<NameValuePair>(); formParams.add(new BasicNameValuePair("data", requestJsonStr)); formParams.add(new BasicNameValuePair("type", "getPackageStream")); HttpEntity entity = new UrlEncodedFormEntity(formParams, "UTF-8"); httppost.setEntity(entity); HttpResponse response = httpclient.execute(httppost); if (response!=null) { int status=response.getStatusLine().getStatusCode(); HttpEntity resEntity = response.getEntity(); InputStream in = resEntity.getContent(); if (status==200) { if (resEntity != null) { logger.debug("in is " + in); FileOutputStream os = null; try { File dir=new File(localPath); if (!dir.exists()) { dir.mkdirs(); } os = new FileOutputStream(localPath+File.separator+fileName); byte[] buffer = new byte[1024]; a6d3 int read; while ((read = in.read(buffer)) > 0) { os.write(buffer, 0, read); } os.flush(); logger.info(fileName+" download success. "); return true; } catch (Exception e) { // TODO: handle exception logger.error("doOutputStreamDownload exception : "+e); throw new Exception("doOutputStreamDownload exception : "+e); }finally{ if (in!=null) { in.close(); } if (os!=null) { os.close(); } EntityUtils.consume(resEntity); } }else{ logger.error("http entity is null. "); return false; } }else{ logger.error("service exec exception. "+inputStream2String(in)); return false; } }else{ logger.error("connect Service Exception! "); return false; } } private static String inputStream2String(InputStream in) throws IOException { //这里的编码规则要与上面的相对应 BufferedReader br = new BufferedReader(new InputStreamReader(in,"UTF-8")); String tempbf; StringBuffer out = new StringBuffer(4096); while ((tempbf = br.readLine()) != null) { out.append(tempbf); } return out.toString(); }
服务器端代码:
public void doDownload(UpdateToolRequest sr,HttpServletResponse response){ logger.info(remoteIP+" get package stream ["+sr.getDownloadPath()+"] ."); long beginTime=System.currentTimeMillis(); InputStream is=null; OutputStream os=null; try { os=response.getOutputStream(); String filePath=sr.getDownloadPath(); File file=new File(filePath); if (!file.exists()) { logger.error(remoteIP+" the package ["+sr.getDownloadPath()+"] isn't exist."); response.setStatus(400); os.write((remoteIP+" the package ["+sr.getDownloadPath()+"] isn't exist.").getBytes()); return; } response.setStatus(200); is=new FileInputStream(file); int block=4*1024; byte[] buffer=new byte[block]; long spreed=sr.getSpreed(); int len; long size=0; long bTime; long nTime; double bSpreed; long outTime; while ((len = is.read(buffer)) > 0) { bTime=System.currentTimeMillis(); os.write(buffer, 0, len); size+=len; os.flush(); Thread.sleep(1); nTime=System.currentTimeMillis(); bSpreed=len*1000/(nTime-bTime); if (spreed!=-1&&spreed<bSpreed) { //超速后计算线程等待时间 outTime=(long) (len*1000/spreed-len*1000/bSpreed); //System.out.println((nTime-bTime)+" ,"+bSpreed+" ,"+spreed+" ,"+"sleep "+outTime); Thread.sleep(outTime); } } long endTime=System.currentTimeMillis(); logger.info(remoteIP+" get package stream success in "+(endTime-beginTime)+" ms. the file "+filePath+" size : "+size+" Byte , spreed "+(size*1000/(endTime-beginTime))+"Byte/s."); } catch (Exception e) { e.printStackTrace(); logger.error(remoteIP+"get package info Exception : " +e); response.setStatus(400); try {os.write((remoteIP+" the package ["+sr.getDownloadPath()+"] isn't exist.").getBytes());} catch (IOException e1) {} }finally{ if (is!=null) { try {if (is!=null) {is.close();}} catch (IOException e) {logger.error(remoteIP+" inputstream close Exception : " +e);} try {if (os!=null) {os.close();}} catch (IOException e) {logger.error(remoteIP+" outputstream close Exception : " +e);} } } }
相关文章推荐
- org.apache.tools.zip.*和org.apache.commons.httpclient.*实现远程文件打包下载,支持中文文件名(转)
- java利用org.apache.http.client下载文件
- 什么是httpclient?& Httpclient使用前提----下载org.apache.commons.httpclient,导入Httpclient的jar包
- 使用AsyncHttpClient下载图片出现org.apache.http.client.HttpResponseException: Content-Type not allowed!
- java应用集锦9:httpclient4.2.2的几个常用方法,登录之后访问页面问题,下载文件
- 【异常】Android中使用localhost:8080或者172.0.0.1:8080访问本地服务器org.apache.http.conn.HttpHostConnectException异常
- org.apache.commons.httpclient.HttpClient 与 org.apache.http.client.HttpClient 区别
- 服务器IIS无法提供某种扩展名的文件的下载或访问某种类型文件提示http 404 错误时的解决办法
- httpclient4.2.2的几个常用方法,登录之后访问页面问题,下载文件
- 关于Xutils框架出现无法访问HttpRequestBase 找不到org.apache.http.client.methods.HttpRequestBase解决方案
- httpclient请求时遇到org.apache.http.client.ClientProtocolException
- 使用Apache HttpClient访问网络(实现手机端注册,服务器返回信息)
- 关于Xutils框架出现无法访问HttpRequestBase 找不到org.apache.http.client.methods.HttpRequestBase解决方案
- 使用Xutils无法访问HttpRequestBase 找不到org.apache.http.client.methods.HttpRequestBase的类文件
- HttpClient使用post方式模拟表单提交数据到服务器并下载服务器文件
- crawler_java应用集锦9:httpclient4.2.2的几个常用方法,登录之后访问页面问题,下载文件_设置代理
- HttpClient4.2.2的几个常用方法,登录之后访问页面问题,下载文件
- 基于HttpClient访问服务器以及上传文件
- FTP文件的上传和下载---org.apache.commons.net.ftp.FTPClient
- org.apache.commons.net.ftp.FTPClient 下载文件提示Software caused connection abort: recv failed