LoadRunner11目前仅支持jdk 1.6版本,在压测时,使用高版本的jdk生成的工具类调用会报错,jdk 1.6来开发调用http协议的工具类,工具使用Apache的httpclient实现,具体步骤如下,在这里下载源码。
1、pom引用
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.14</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<classifier>jdk15</classifier>
<version>2.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.13</version>
</dependency>
2、Content-Type为multipart/form-data的POST请求工具类实现,并支持文件上传,代码如下
private static final Integer CONNECT_TIMEOUT = 15000;
private static final Integer REND_TIMEOUT = 60000;
/**
* 使用httpClient发送post请求,contentType 类型为application/x-www-form-urlencoded
* @param httpurl 请求的url
* @param params 请求的参数
* @param headers 请求头
* @param filePathMap 上传文件
* @return
* @throws Exception
*/
public static EdsmHttpResponse sendPostFormRequst(String httpurl, Map<String, Object> params,
Map<String, Object> headers, Map<String, String> filePathMap) throws Exception {
EdsmHttpResponse resultResponse = null;
CloseableHttpClient httpClient = createSSLClientDefault(httpurl);
// 创建Post请求
HttpPost httpPost = new HttpPost(httpurl);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
String boundary = "DSPSBoundary" + System.currentTimeMillis();
builder.setBoundary(boundary);
httpPost.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
// 设置其他自定义 headers
if (headers != null && !headers.isEmpty()) {
for (Map.Entry<String, Object> header : headers.entrySet()) {
httpPost.setHeader(header.getKey(), header.getValue().toString());
}
}
//设置参数
if (params != null && !params.isEmpty()) {
Set<String> keySet = params.keySet();
Iterator<String> iterator = keySet.iterator();
while (iterator.hasNext()) {
String key = iterator.next();
Object value = params.get(key);
builder.addTextBody(key, (String) value,ContentType.create("text/plain", Consts.UTF_8));
}
}
//添加文件
if ((filePathMap != null) && (!filePathMap.isEmpty())) {
for (Map.Entry<String, String> filePath : filePathMap.entrySet()) {
File file = new File(filePath.getValue());
if(file.exists()) {
FileBody bin = new FileBody(file);
builder.addPart(filePath.getKey(),bin);
}
}
}
HttpEntity multipart = builder.build();
httpPost.setEntity(multipart);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT)
.setSocketTimeout(CONNECT_TIMEOUT).setConnectionRequestTimeout(REND_TIMEOUT).build();
httpPost.setConfig(requestConfig);
// 响应模型
CloseableHttpResponse response = null;
try {
// 由客户端执行(发送)Post请求
response = httpClient.execute(httpPost);
// 从响应模型中获取响应实体
HttpEntity responseEntity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
String result = "";
if (statusCode != 200) {
}
if (responseEntity != null) {
result = EntityUtils.toString(responseEntity, "UTF-8");
}
resultResponse = new EdsmHttpResponse(statusCode, result);
return resultResponse;
} catch (ClientProtocolException e) {
throw new Exception("ClientProtocolException", e);
} catch (ParseException e) {
throw new Exception("ParseException", e);
} catch (ConnectException e) {
throw new Exception("ConnectException", e);
} catch (SocketTimeoutException e) {
throw new Exception("SocketTimeoutException", e);
} catch (IOException e) {
throw new Exception("IOException", e);
} finally {
try {
// 释放资源
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
}
}
}
3、Content-Type为multipart/form-data的GET请求工具类实现,代码如下
/**
* 发送GET请求
*
* @param httpurl 请求的部分url
* @param map
* @return
* @throws Exception
*/
public static EdsmHttpResponse sendGetRequst(String httpurl, Map<String, String> map) throws Exception {
EdsmHttpResponse resultResponse = null;
CloseableHttpClient httpClient = createSSLClientDefault(httpurl);
StringBuffer sb = new StringBuffer();
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
for (Entry<String, String> entry : map.entrySet()) {
parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
String str = EntityUtils.toString(new UrlEncodedFormEntity(parameters, "utf-8"));
sb.append(httpurl);
sb.append("?");
sb.append(str);
// 创建Get请求
HttpGet httpGet = new HttpGet(sb.toString());
String boundary = "DSPSBoundary" + System.currentTimeMillis();
httpGet.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT)
.setSocketTimeout(CONNECT_TIMEOUT).setConnectionRequestTimeout(REND_TIMEOUT).build();
httpGet.setConfig(requestConfig);
// 响应模型
CloseableHttpResponse response = null;
try {
// 由客户端执行(发送)GET请求
response = httpClient.execute(httpGet);
// 从响应模型中获取响应实体
HttpEntity responseEntity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
String result = "";
if (statusCode != 200) {
}
if (responseEntity != null) {
result = EntityUtils.toString(responseEntity, "UTF-8");
}
resultResponse = new EdsmHttpResponse(statusCode, result);
return resultResponse;
} catch (ClientProtocolException e) {
throw new Exception("ClientProtocolException", e);
} catch (ParseException e) {
throw new Exception("ParseException", e);
} catch (ConnectException e) {
throw new Exception("ConnectException", e);
} catch (SocketTimeoutException e) {
throw new Exception("SocketTimeoutException", e);
} catch (IOException e) {
throw new Exception("IOException", e);
} finally {
// 释放资源
if (response != null) {
try {
response.close();
} catch (IOException e) {
}
}
if (httpClient != null) {
try {
httpClient.close();
} catch (IOException e) {
}
}
}
}
4、Content-Type为application/json的POST请求工具类实现,代码如下
/**
* 使用httpClient发送数据类型application/json的post请求
*
* @param httpurl 请求地址
* @param params 请求参数
* @param headers 请求头
* @return
* @throws Exception
*/
public static EdsmHttpResponse sendPostJsonRequst(String httpurl, Map<String, Object> params,
Map<String, Object> headers) throws Exception {
EdsmHttpResponse resultResponse = null;
CloseableHttpClient httpClient = createSSLClientDefault(httpurl);
// 创建Post请求
HttpPost httpPost = new HttpPost(httpurl);
if (params != null && !params.isEmpty()) {
// post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
JSONObject fromObject = JSONObject.fromObject(params);
httpPost.setEntity(new StringEntity(fromObject.toString(), "UTF-8"));
}
httpPost.setHeader("Content-Type", "application/json");
// 设置其他自定义 headers
if (headers != null && !headers.isEmpty()) {
for (Map.Entry<String, Object> header : headers.entrySet()) {
httpPost.setHeader(header.getKey(), header.getValue().toString());
}
}
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT)
.setSocketTimeout(CONNECT_TIMEOUT).setConnectionRequestTimeout(REND_TIMEOUT).build();
httpPost.setConfig(requestConfig);
// 响应模型
CloseableHttpResponse response = null;
try {
// 由客户端执行(发送)Post请求
response = httpClient.execute(httpPost);
// 从响应模型中获取响应实体
HttpEntity responseEntity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
String result = "";
if (statusCode != 200) {
}
if (responseEntity != null) {
result = EntityUtils.toString(responseEntity, "UTF-8");
}
resultResponse = new EdsmHttpResponse(statusCode, result);
return resultResponse;
} catch (ClientProtocolException e) {
throw new Exception("ClientProtocolException", e);
} catch (ParseException e) {
throw new Exception("ParseException", e);
} catch (ConnectException e) {
throw new Exception("ConnectException", e);
} catch (SocketTimeoutException e) {
throw new Exception("SocketTimeoutException", e);
} catch (IOException e) {
throw new Exception("IOException", e);
} finally {
try {
// 释放资源
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
}
}
}
5、对于HTTPS协议,跳过客户端证书的验证,具体实现如下
/**
* 创建默认的http链接
* @param httpurl 请求的url
* @return
*/
public static CloseableHttpClient createSSLClientDefault(String httpurl) {
if (StringUtils.isNotBlank(httpurl)) {
String srt = httpurl.substring(0, 5);
if("https".equalsIgnoreCase(srt)) {
try {
// 使用 loadTrustMaterial() 方法实现一个信任策略,信任所有证书
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
// 信任所有
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
// 有效的SSL会话并匹配到目标主机。
HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
}
}
return HttpClients.createDefault();
}
5、调用方法如下
public static void main(String[] args) {
String url = "";//请求的URL
Map<String, Object> params = new HashMap<String, Object>();//传参
Map<String, Object> headers = new HashMap<String, Object>();//请求头
Map<String, String> filePathMap = new HashMap<String, String>();//需要上传的文件
try {
//发起application/x-www-form-urlencoded的post请求工具类
RestfulHttpUtil.sendPostFormRequst(url, params, headers, filePathMap);
} catch (Exception e) {
e.printStackTrace();
}
try {
//发起application/json的post请求
RestfulHttpUtil.sendPostJsonRequst(url, params, headers);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Map<String, String> map = new HashMap<String, String>();//的参数
try {
//发起multipart/form-data; 的get请求
RestfulHttpUtil.sendGetRequst(url, map);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
对于未实现的Content-Type为application/json的GET请求,可以仿照multipart/form-data的GET进行实现。
|