org.apache.http.client.HttpClient 访问服务器限速下载文件
来源:互联网 发布:钢琴软件电脑版 编辑:程序博客网 时间:2024/05/29 03:42
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]; 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);} } } }
0 0
- org.apache.http.client.HttpClient 访问服务器限速下载文件
- org.apache.http.client.HttpClient
- org.apache.http.client.HttpClient
- 2.使用org.apache.http.client.HttpClient访问网络
- org.apache.http.client.httpclient报错:
- java利用org.apache.http.client下载文件
- org.apache.commons.httpclient.HttpClient 与 org.apache.http.client.HttpClient 区别
- org.apache.http.client.HttpClient和org.apache.commons.httpclient.HttpClient的区别
- org.apache.commons.httpclient.HttpClient 与 org.apache.http.client.HttpClient 区别
- apache.http.client.HttpClient
- httpclient请求时遇到org.apache.http.client.ClientProtocolException
- httpclient请求时遇到org.apache.http.client.ClientProtocolException
- java 使用httpclient出错org.apache.http.client.ClientProtocolException
- org.apache.http.client.HttpClient get/post请求
- java.lang.ClassNotFoundException: org/apache/http/client/HttpClient
- org.apache.http.client.CircularRedirectException
- Java用org.apache.http.client的HttpClient发送Post请求 可获取返回Header
- Java--org.apache.http.client的HttpClient发送Post请求,获取返回Header
- java关于form表单的序列化提交(包括带有file)
- 熟悉公司业务springboot和dataTable和validate在项目中的应用(1)
- 工具使用说明-IntelliJ IDEA快捷键
- 项目中出现两个src文件如何处理
- Android 系列 1.1了解Android应用程序架构
- org.apache.http.client.HttpClient 访问服务器限速下载文件
- plsql连接方法
- 关于oracle中procedure和function返回cursor类型的变量
- java synchronized类锁,对象锁详解(转载)
- 正则表达式
- LeetCode 3Sum Closest
- 使用apache-xmlrpc-3.1.3 编写Java XML-RPC Client
- Gradle's dependency cache may be corrupt解决方法
- 输入流转字节流