如题,我想用HttpClient来发送一个请求,并获取返回的数据,但是请求的时间不能超过5秒,所以我就这样写了,但感觉哪地方有些不对
//用来发送请求的主方法
public static String post(String href){
if(href==null||href.equals(""))
return null;
String response=null;
try{
System.out.println("****发送"+href+"请求");
TimeThread t=new TimeThread(href);
long start=System.currentTimeMillis();
long time=5000;
t.start();
/**
* 此处用线程去获取连接数据,并在此循环中在规定时间内取返回数据,达到时间内没有数据,抛出超时异常
*/
while(response==null&&(System.currentTimeMillis()-start)<time){
response=t.getResponse();
if(response!=null){
System.out.println("****连接成功");
return response;
}
}
throw new RuntimeException("Connect time out.");
}catch (Exception e) {
System.out.println("****请求失败,Cause by:"+e.getMessage());
}
return response;
}
另线程类
class TimeThread extends Thread{
String href;
String response;
public TimeThread(String href){
this.href=href;
}
@Override
public void run() {
response=HttpClientHelper.read(href);
}
public String getResponse() {
return response;
}
}
------解决方案--------------------
感觉应该是可以的,因为没法运行一下代码所以没法确定。 但是有一个问题,函数体线程等不到响应而抛出异常时,应该将TimeThread 中断,否则这个线程会一直等到获取到请求,而这个请求却没有响应代码。
------解决方案--------------------
可行, 但是这样实现很奇怪。 常规做法是HttpClientHelper.read(href)的时候设置http请求响应时长, 因为这样可以理解为一次请求最多5秒, 这个时间基本上是对服务器处理及网络的限制, 而你这样做连客户端的代码运行时间也一并限制了, 没这个必要, 实现起来也不雅