loadrunner Java协议发送http请求
1.Maven添加依赖
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.12</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.13</version>
</dependency>
2.脚本
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;import org.apache.commons.lang.RandomStringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSONObject;
public class Actions
{
private String outTradeNo="";
public String send() {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
String result = "";
try {
// 通过址默认配置创建一个httpClient实例
httpClient = HttpClients.createDefault();
String url = "http://ip:port/service"; // 根据环境配置
HttpPost httpPost = new HttpPost(url);
// 设置配置请求参数
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 连接主机服务超时时间
.setConnectionRequestTimeout(35000)// 请求超时时间
.setSocketTimeout(60000)// 数据读取超时时间
.build();
// 为httpGet实例设置配置
httpPost.setConfig(requestConfig);
StringEntity entity = new StringEntity(toJSONObject(), "UTF-8");entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");System.out.println(toJSONObject());
httpPost.setEntity(entity);
// 执行请求得到返回对象
response = httpClient.execute(httpPost);
// 通过返回对象获取返回数据
HttpEntity rspEntity = response.getEntity();
// 通过EntityUtils中的toString方法将结果转换为字符串
result = EntityUtils.toString(rspEntity);
if (response.getStatusLine().getStatusCode()==200) {
if (result.contains("responsecode")) {
}
}
}catch (ClientProtocolException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}finally {
// 关闭资源
if(null != response) {
try {
response.close();
}catch (IOException e) {
e.printStackTrace();
}
}
if(null != httpClient) {
try {
httpClient.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}private String toJSONObject() {
JSONObject respJson = new JSONObject();
respJson.put("F007", "q");
respJson.put("F011", new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()));
// respJson.put("F037", "a4" + RandomStringUtils.randomNumeric(10));
respJson.put("F037", "q");
respJson.put("F039", "00");
System.out.println(respJson.toString());
return respJson.toString();
}}
本文来自博客园,作者:up~up,转载请注明原文链接:https://www.cnblogs.com/soft-engineer/p/14985081.html