一、当发送get请求时,会遇到断网、链接超时等异常状况,通过测试用例,提供两种方式进行请求重发
1、test()方法中的示例,是在当前主线程中,一直循环重发请求,一直到请求获得相应后不在重发,发送请求的时间间隔是2秒。
2、main方法中的示例,是在第一次发送请求时捕获到异常信息,另外开启一个子线程,在子线程中循环发送请求,一直到请求获得响应为止,子线程中每次发送请求的时间间隔是1秒。
/**
* @auther Administrator
* date 2018年3月22日
* @time 上午11:12:07
*/
package com.yooyii.qdp.test;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import javax.swing.Timer;
import java.util.*;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import net.dongliu.requests.Requests;
/**
* @author Administrator
*
*/
public class ResendTest {
// public static void main(String[] args) {
// java.util.Timer timer = new java.util.Timer();// 实例化Timer类
// timer.schedule(new TimerTask() {
// @Override
// public void run() {
// System.out.println("退出");
// this.cancel();
// }
// }, 5000);// 这里百毫秒
// System.out.println("本程序存在5秒后自动退出");
// }
@Test
public void test() {
while (true) {
String url2 = "https://www.baidu.com";
String report = "";
try {
report = Requests.get(url2).send().readToText();
if (StringUtils.isNotBlank(report)) {
System.out.println("成功!");
break;
}
System.out.println(report);
} catch (Exception e) {
System.out.println("重发!");
}
try {
Robot r = new Robot();
System.out.println( "延时2秒");
r.delay(2000);
} catch (AWTException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
String url2 = "https://www.baidu.com";
String report = "";
try {
report = Requests.get(url2).send().readToText();
if (StringUtils.isNotBlank(report)) {
System.out.println("成功!");
}
} catch (Exception e) {
System.out.println("请求异常,需重新请求!");
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
String url2 = "https://www.baidu.com";
System.out.println("延迟");
try {
String report = Requests.get(url2).send().readToText();
if (StringUtils.isNotBlank(report)) {
System.out.println("重发成功!");
break;
}
} catch (Exception e2) {
System.out.println("请求异常,需重新请求!");
}
try {
Thread.sleep(1000);
} catch (InterruptedException e2) {
// TODO: handle exception
}
}
}
});
thread.start();
}
}
}