使用Hessian中,在Java模拟客户端的时候可能存在需要向Hessian报文头信息设置一些参数,如token信息。默认的HessianProxyFactory对没有方法设置报文头的方法。以下方法可以做到。
1.新建自己的HessianProxyFactory继承com.connection.ForwardHessianConnectionFactory
/**
* 接口调用的HessianConnectionFactory
* 重写Hessian的HessianURLConnectionFactory向报文头添加接入端的控制信息
*
* @author ZhangMingxue
* @version 1.0
* @time 2013下午04:49:30
* @JDK 1.6
*/
public class ForwardHessianConnectionFactory extends
HessianURLConnectionFactory {
// 报文头参数
private Map<String, String> headerParamMap = null;
/**
* 报文头参数,通过构造方法传入
*
* @param headerParamMap
*/
public ForwardHessianConnectionFactory(Map<String, String> headerParamMap) {
this.headerParamMap = headerParamMap;
}
@Override
public HessianConnection open(URL url) throws IOException {
HessianURLConnection hessianURLConnection = (HessianURLConnection) super
.open(url);
if (null != headerParamMap && !headerParamMap.isEmpty()) {
Set<String> keySet = headerParamMap.keySet();
for (String key : keySet) {
// 向报文头中添加参数
hessianURLConnection.addHeader(key, headerParamMap.get(key));
}
}
return hessianURLConnection;
}
}
2.创建HessianProxyFactory
/**
* 创建HessianProxyFactory
*
* @param jsc
* @return
*/
public HessianProxyFactory createHessianProxyFactory(JavaSamplerContext jsc) {
HessianProxyFactory hessianProxyFactory = new HessianProxyFactory();
// Request的Header设置参数
Map<String, String> headerParamMap = addRequestHeaderParams(jsc);
// 创建自己的HessianConnectionFactory
HessianConnectionFactory hessianConnectionFactory = new ForwardHessianConnectionFactory(
headerParamMap);
hessianConnectionFactory.setHessianProxyFactory(hessianProxyFactory);
hessianProxyFactory.setConnectionFactory(hessianConnectionFactory);
return hessianProxyFactory;
}
/**
* 接口接用请求转发
*
* @param jsc
* @return
*/
public Map<String, String> addRequestHeaderParams(JavaSamplerContext jsc) {
Map<String, String> headerParamMap = new HashMap<String, String>();
headerParamMap.put("xxxxx1", jsc.getParameter("id"));
headerParamMap.put("xxxxx2", jsc.getParameter("authToken"));
return headerParamMap;
}
3.客户端使用自己的HessianProxyFactory,获取远程接口。
public IPropose buildRemoterServer(JavaSamplerContext jsc) {
HessianProxyFactory hessianProxyFactory = createHessianProxyFactory(jsc);
IPropose iPropose = null;
try {
StringBuffer url = createServerURL(jsc,
"xxx.xxx.xxxx.xxxxServlet");
iPropose = (IPropose) hessianProxyFactory.create(IPropose.class,
url.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
return iPropose;
}
@Override
public SampleResult runTest(JavaSamplerContext jsc) {
SampleResult result = new SampleResult();
result.sampleStart();
try {
IPropose iPropose = buildRemoterServer(jsc);
Object bo = iPropose.createPl();//调用远程服务器方法
result.sampleEnd();
} catch (Exception e) {
result.setSuccessful(false);
result.setResponseMessage(e.getMessage());
e.printStackTrace();
}
return result;
}
以上的JavaSamplerContext对象可以简单理解为Map类型的参数,由jmeter测试工具创建,主要用于存放测试的参数,根Hessian没有关系,主要是我的客户端是Jmeter,如果是客户端采用的是其它技术可以把JavaSamplerContext换成Map.