LoadRunner Java Vuser 实现 Get/Post 示例
安装Java运行环境,下载一个Tomcat,%WebRoot%新建一个default.jsp文件,代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<html>
<head>
<title>Get/Post</title>
</head>
<body>
This is my JSP page. <br>
<%
String a=request.getParameter("a");
if(null!=a){
out.print(a);out.print("<br>");
}
String b=request.getParameter("b");
if(null!=b){
out.print(b);out.print("<br>");
}
%>
</body>
</html>打开LoadRunner,新建java vuser脚本,代码如下:
import lrapi.lr;
import java.net.URL;
import java.net.URLConnection;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.io.PrintWriter;
public class Actions
{
public int init() throws Throwable {
return 0;
}//end of init
public int action() throws Throwable {
lr.output_message(sendGet("http://localhost:8080/default.jsp","a=3"));
lr.output_message(sendPost("http://localhost:8080/default.jsp","b=4"));
return 0;
}//end of action
public static String sendGet(String url,String param){
String result = "";
try{
String urlName = url + "?"+param;//
URL U = new URL(urlName);
URLConnection connection = U.openConnection();
connection.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine())!= null){
result += line;
}
in.close();
}catch(Exception e){
System.out.println("Empty !"+e);
}
return result;
}
public static String sendPost(String url, String param) {
String result = "";
try {
URL httpurl = new URL(url);
HttpURLConnection httpConn = (HttpURLConnection) httpurl.openConnection();
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
PrintWriter out = new PrintWriter(httpConn.getOutputStream());
out.print(param);
out.flush();
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
String line;
while ( (line = in.readLine()) != null) {
result += line;
}
in.close();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Empty !" + e);
}
return result;
}
public int end() throws Throwable {
return 0;
}//end of end
}启动Tomcat,运行LoadRunner,输出结果如下:
Virtual User Script started
Starting action vuser_init.
Ending action vuser_init.
Running Vuser...
Starting iteration 1.
Starting action Actions.
<html> <head> <title>Get/Post</title> </head> <body> This is my JSP page. <br> 3<br> </body></html>
<html> <head> <title>Get/Post</title> </head> <body> This is my JSP page. <br> 4<br> </body></html>
Ending action Actions.
Ending iteration 1.
Ending Vuser...
Starting action vuser_end.
Ending action vuser_end.
Vuser Terminated.oadRunner Java Vuser 实现Get/Post 就这么简单的实现了 ~
实际上,直接“import lrapi.web;”就可以使用和Web/Http协议的大部分Web函数了。