java的http中get请求的重发机制

一、当发送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();
		}
	}
	
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值