package com.*.casLogin;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;
import com.*.jmeter.util.CASHttpClient;
public class CASLogin extends AbstractJavaSamplerClient {
private String url;
private String username;
private String password;
private static final String _eventId = "submit";
private String lt;
private SampleResult results;
private static final String regex = "(\\d+\\.\\d+\\.\\d+\\.\\d+)\\:(\\d+)";
// 这个方法是用来自定义java方法入参的。
// params.addArgument("num1","");表示入参名字叫num1,默认值为空。
public Arguments getDefaultParameters() {
Arguments params = new Arguments();
params.addArgument("url", "");
params.addArgument("username", "");
params.addArgument("password", "");
return params;
}
//每个线程测试前执行一次,做一些初始化工作;
public void setupTest(JavaSamplerContext context) {
results = new SampleResult();
results.setSampleLabel( "JAVA【CAS登录-返回重定向地址】");
results.setDataEncoding("UTF-8");//因为响应的数据有中文,所以最好先设置编码
url = context.getParameter("url");
username = context.getParameter("username");
password = context.getParameter("password");
results.setSamplerData("url:"+url+"\n"+"username:"+username+"\n"+"password:"+password+"\n");
}
@Override
public SampleResult runTest(JavaSamplerContext context) {
try {
results.sampleStart();// jmeter 开始统计响应时间标记
lt = CASHttpClient.getCasLt(url);
if ("".equals(lt)||null==lt) {
throw new Exception("lt没有取到~!");
}
String redirect_url = CASHttpClient.sendCasLogin(url, username, password, lt,_eventId);
redirect_url = rebuildRedirectUrl(redirect_url);
if (redirect_url != null && redirect_url.length() > 0) {
System.out.println("redirect_url:"+redirect_url);
results.setResponseData(redirect_url, "UTF-8");
results.setContentType("application/json");
//results.setDataType(SampleResult.TEXT);
}
// System.out.println(resultData);
results.setSuccessful(true);
} catch (Throwable e) {
results.setSuccessful(false);
e.printStackTrace();
}finally {
results.sampleEnd();// jmeter 结束统计响应时间标记
}
return results;
}
private String rebuildRedirectUrl(String redirect_url) {
Pattern p = Pattern.compile(regex);
Matcher m =