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
原创粉丝点击