您的位置:首页 > 理论基础 > 计算机网络

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);}
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐