【脚本开发】:性能测试-Java虚拟用户实现下载脚本

方法一,采用java vuer开发

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import lrapi.lr;
public class Actions {
public int init() throws Throwable
{
return 0;
}//end of init
public int action() throws Throwable
{
int DownLoadSize = 0;
String path = "c:\\temp\\";  //设置下载文件保存路径
String vuid = String.valueOf(lr.get_vuser_id()); //获取当前虚拟用户ID并转换成字符串
DownLoadSize = UrlTools.getHttpFileByUrl("http://forum.ubuntu.org.cn/download/file.php?id=129973&sid=78fc8d76767ef49b606595824ceb963d",vuid,path); //调用UrlTools.getHttpFileByUrl()
return 0;
}//end of action
public int end() throws Throwable
{
return 0;
}//end of end }
class UrlTools
{
public static int getHttpFileByUrl(String address,String userid,String path)
{
//定义下面需要用到的变量
URL url;
URLConnection conn = null;
int BUFF_SIZE = 1024;
byte[] buf = new byte[BUFF_SIZE];
int DownLoadSize = 0;
BufferedInputStream bis;
FileOutputStream fos = null;
int size = 0;
try
{
  url = new URL(address); //address为传递进来需要下载的链接
  conn =  url.openConnection();//使用url实例化需要下载的链接
  bis = new BufferedInputStream(conn.getInputStream()); //把需要下载的文件内容保存在bis这个输入流中
  fos = new FileOutputStream(path+"\"+userid+"test000001"+“.pdf”));//组成完整路径,并实例化到输出流,这里可以进行参数化,如参数化文件名, // 路径需要事先手动创建好,当然你也可以在脚本中创建实现不同的路径
  System.out.println("需要下载的文件大小为:" + conn.getContentLength()/1024 + "k");
  while((size = bis.read(buf)) != -1)   #按照设置的buf大小写文件并记录下载的大小
  {
    fos.write(buf,0,size);
  DownLoadSize = DownLoadSize+size;
  }
  bis.close();
  fos.close();
System.out.println("用户" + userid + "下载" + url +"完成!");
}

catch(MalformedURLException e) {   System.out.println("下载发生异常:");   e.printStackTrace(); }

catch(IOException e) {   System.out.println("下载发生异常:");   e.printStackTrace(); }   return DownLoadSize/1024; } }

方法二:将getHttpFileByUrl函数单独封装起来,在lr中调用,在Eclipse中新建一个.java

 

posted @ 2018-05-09 15:31  fy-  阅读(379)  评论(0编辑  收藏  举报