大概内容是,从txt中读取接口信息,将返回信息存在另一个txt文件里
1.大概思路是 先调登录接口,拿到JSESSIONID就是下图,调其他接口时将JSESSIONIDset到请求头里,2.验证码的问题是这样解决的:我做的项目生成验证码存在redis里,调登录接口时从redis里取出验证码,与输入的验证码进行比较,所以为了实现自动化,向redis里塞一个自定义的验证码。
下图是项目目录结构
这是文件样板按 /t 分割 参数是json格式
#####redis 配置文件
server.port=8080
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=172.16.43.104
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=beap123
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=20
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=10
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=1000
主流程代码
@Service
public class MainFuncService {
@Value("${resturl}")
private String url;
@Value("${sourcesfile}")
private String sourcesfile;
@Autowired
private OperateTxtUtil operateTxtUtil;
@Autowired
private ObtainResponseUtil obtainResponseUtil;
public void start() {
try {
String encoding = "GBK";
File file = new File(sourcesfile);
if (file.isFile() && file.exists()) {
InputStreamReader read = new InputStreamReader(
new FileInputStream(file), encoding);
BufferedReader bufferedReader = new BufferedReader(read);
String lineTXT = null;
//先读取第一行,下面从第二行开始读
bufferedReader.readLine();//上面是读取文件内容
operateTxtUtil.writeToTxt(
"序号" + "\t" + "接口" + "\t" + "参数" + "\t" + "响应" + "\t" + "结果" + "\t" + "实际响应");
while ((lineTXT = bufferedReader.readLine()) != null) {
String[] item = lineTXT.toString().trim().split("\t");//将字段按/t分割
String num = item[0];
String restful = item[1];//url
String params = item[2];//参数
String modelResponse = item[3];//模板响应,事先请求好的
JSONObject jsonObject = new JSONObject(params);
String response = **obtainResponseUtil**.requestOCRForHttp(url + restful, jsonObject);//将读取的文件内容处理好后开始发送post请求
if (modelResponse.equals(response)) {
**operateTxtUtil.writeToTxt**(
num + "\t" + url + restful + "\t" + jsonObject + "\t" + modelResponse + "\t" + "通过"
+ "\t"
);
} else {
operateTxtUtil.writeToTxt(
num + "\t" + url + restful + "\t" + jsonObject + "\t" + modelResponse + "\t" + "未通过"
+ "\t" + response);
}
}
System.out.println("执行完成");
read.close();
} else {
System.out.println("找不到指定的文件!");
}
} catch (Exception e) {
System.out.println("读取文件内容操作出错");
e.printStackTrace();
}
}
}
发送http请求
@Component
public class ObtainResponseUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (ObtainResponseUtil.applicationContext == null) {
ObtainResponseUtil.applicationContext = applicationContext;
}
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
public static <T> T getBean(String name, Class<T> clazz) {
return getApplicationContext().getBean(name, clazz);
}
private StringRedisTemplate stringRedisTemplate;
public static String SESSION_ID;
@Autowired
private SessionUtil sessionUtil;
@Value("${username111}")
private String username;
@Value("${password}")
private String password;
@Value("${authcode}")
private String authcode;
@Value("${Host}")
private String Host;
public String requestOCRForHttp(String url, JSONObject jsonObject)
throws Exception {
String result = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
/** HttpPost */
HttpPost httpPost = new HttpPost(url);
//遍历参数
List<NameValuePair> params = new ArrayList<NameValuePair>();
Iterator<?> it = jsonObject.keys();
while (it.hasNext()) {
String key = it.next().toString();
String value = jsonObject.getString(key);
params.add(new BasicNameValuePair(key, value));/
}
try {
stringRedisTemplate = (StringRedisTemplate) ObtainResponseUtil
.getBean(Class.forName("org.springframework.data.redis.core.StringRedisTemplate"));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//向redis塞验证码
stringRedisTemplate.opsForValue().set("nullstrCode", "1111");//向redis塞验证码
//stringRedisTemplate.expire("nullstrCode", Duration.ofSeconds(120));
//登录接口的参数
Map<String, String> map = new HashMap<String, String>();
map.put("username", username);
map.put("password", password);
map.put("authcode", authcode);//验证码与往redis里塞的一致
String charset = "UTF-8";
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
if (StringUtils.isEmpty(SESSION_ID)) {
SESSION_ID = **sessionUtil**.doPost(map, charset);//**获取JSESSIONID**
}
httpPost.setHeader("Cookie", "JSESSIONID" + "=" + SESSION_ID);//**将JSESSIONIDset到其他接口的请求头里**
httpPost.setHeader("Host", Host);
httpPost.setHeader("User-Agent", "Mozilla/5.0");
/** HttpResponse */
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
try {
HttpEntity httpEntity = httpResponse.getEntity();
result = EntityUtils.toString(httpEntity, "utf-8");
EntityUtils.consume(httpEntity);
} finally {
try {
if (httpResponse != null) {
httpResponse.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
#####调用登录接口用来获取JSESSIONID
```java
@Service
public class SessionUtil {
@Value("${resturl}")
private String url;
public String doPost(Map<String, String> map, String charset) {
CloseableHttpClient httpClient = null;
HttpPost httpPost = null;
String result = null;
try {
CookieStore cookieStore = new BasicCookieStore();
httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
httpPost = new HttpPost(url + "/users/sign_in");
List<NameValuePair> list = new ArrayList<NameValuePair>();
Iterator<Entry<String, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Entry<String, String> elem = (Entry<String, String>) iterator.next();
list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
}
if (list.size() > 0) {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
httpPost.setEntity(entity);
}
httpClient.execute(httpPost);
String JSESSIONID = null;
String cookie_user = null;
List<Cookie> cookies = cookieStore.getCookies();
// 遍历拿到的cookie
for (int i = 0; i < cookies.size(); i++) {
if (cookies.get(i).getName().equals("JSESSIONID")) {
JSESSIONID = cookies.get(i).getValue();
result = JSESSIONID;
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
}
将返回信息写进文件
@Service
public class OperateTxtUtil {
@Value("${resultfile}")
private String resultfile;
public String writeToTxt(String data) {
try {
File file = new File(resultfile);
if (!file.exists()) {
// 创建新文件,有同名的文件的话直接覆盖
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(file, true);
OutputStreamWriter osw = new OutputStreamWriter(fos,"utf-8");
BufferedWriter bw = new BufferedWriter(osw);
bw.write(data);
bw.newLine();
bw.flush();
bw.close();
osw.close();
fos.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
}
return null;
}
}