URLConnection类常见的超时处理就是调用其setConnectTimeout和setReadTimeout方法:

  1. setConnectTimeout:设置连接主机超时(单位:毫秒)
  2. setReadTimeout:设置从主机读取数据超时(单位:毫秒)

还有一种比较另类的就是利用java Object对象的wait()和notify()、notifyAll()方法,利用线程的等待和通知机制处理urlConnection的超时,下面直接贴代码:

public class HttpConnProcessThread implements Runnable {

    public boolean isStop = false;

    public boolean readOK = false;

    private HttpURLConnection reqConnection = null;

    public Thread readingThread;

    private int readLen;

    private String msg = null;

    private String reqMethod;

    private byte[] data;

    /**
* ReadThread constructor comment.
*/
public HttpConnProcessThread(HttpURLConnection reqConnection, String msg, String reqMethod ) {
super();
this.reqConnection = reqConnection;
this.msg = msg;
this.reqMethod = reqMethod;
} public void run() { InputStream input = null;
OutputStream output = null; try{
//reqConnection.connect();
output = reqConnection.getOutputStream();
if ("post".equalsIgnoreCase(reqMethod) && msg != null && msg.length() >0)
{
output.write(msg.getBytes());
output.close();
output = null;
} // 处理HTTP响应的返回状态信息
int responseCode = reqConnection.getResponseCode();// 响应的代码if( responseCode != 200 )
System.out.println("connect failed! responseCode = " + responseCode + " msg=" + reqConnection.getResponseMessage()); input = reqConnection.getInputStream(); int len;
byte[] buf = new byte[2048];
readLen = 0;
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
       // 读取inputStream
while (!isStop)
{
len = input.read(buf);
if (len <= 0)
{
this.readOK = true;
input.close();
data=outStream.toByteArray();
break;
}
outStream.write(buf, 0, len);
readLen += len;
}
}
catch( IOException ie)
{}
catch(Exception e)
{}
finally
{
try{
reqConnection.disconnect();
if( input != null )
input.close();
if( output != null )
output.close(); //唤醒线程,跳出等待
wakeUp();
}catch(Exception e)
{ }
}
} public String getMessage(){
if (!readOK) //超时
{
return "";
} if (readLen <= 0) {
return "";
}
return new String(data, 0, readLen);
} public void startUp() {
this.readingThread = new Thread(this);
readingThread.start();
} //唤醒线程,不再等待
private synchronized void wakeUp() {
notifyAll();
} public synchronized void waitForData(int timeout)
{
try {
//指定超时时间,等待connection响应
wait(timeout);
}
catch (Exception e)
{
} if (!readOK)
{
isStop = true;
try{
//中断线程
if( readingThread.isAlive() )
readingThread.interrupt();
}catch(Exception e)
{ }
}
} public static main(String[] args){
String msg="";
URL reqUrl = new URL("http://127.0.0.1:8080/"); // 建立URLConnection连接
reqConnection = (HttpURLConnection) reqUrl.openConnection();
HttpConnProcessThread rec = new HttpConnProcessThread(reqConnection, msg, "post" );
rec.startUp();
   // 如果顺利连接到并读完数据,则跳出等待,否则等待超时
rec.waitForData(2000); String retMessage = rec.getMessage();
}
}

Http请求超时的一种处理方法的更多相关文章

  1. Nodejs回调加超时限制两种实现方法

    odejs回调加超时限制两种实现方法 Nodejs下的IO操作都是异步的,有时候异步请求返回太慢,不想无限等待回调怎么办呢?我们可以给回调函数加一个超时限制,到一定时间还没有回调就表示失败,继续后面的 ...

  2. 关于TcpClient,Socket连接超时的几种处理方法

    用TcpClient做通信的时候,经常发现网络连接不通的时候,代码就卡死在那里,TcpClient竟然没有超时的设定 泪奔啊 看来微软不是把所有工具准备得妥妥当当的啊 没办法 现在用线程来包装一下这个 ...

  3. [Swift]Alamofire:设置网络请求超时时间【timeout】的两种方式

    两种方式作用相同,是同一套代码的两种表述. 第一种方式:集聚. 直接设置成员属性(全局属性),这种方法不能灵活修改网络请求超时时间timeout. 声明为成员属性: // MARK: - 设置为全局变 ...

  4. [转]axios请求超时,设置重新请求的完美解决方法

    自从使用Vue2之后,就使用官方推荐的axios的插件来调用API,在使用过程中,如果服务器或者网络不稳定掉包了, 你们该如何处理呢? 下面我给你们分享一下我的经历. 具体原因 最近公司在做一个项目, ...

  5. Django的POST请求时因为开启防止csrf,报403错误,及四种解决方法

    Django默认开启防止csrf(跨站点请求伪造)攻击,在post请求时,没有上传 csrf字段,导致校验失败,报403错误 解决方法1: 注释掉此段代码,即可. 缺点:导致Django项目完全无法防 ...

  6. 服务器编程入门(13) Linux套接字设置超时的三种方法

    摘要:     本文介绍在套接字的I/O操作上设置超时的三种方法. 图片可能有点宽,看不到的童鞋可以点击图片查看完整图片.. 1 调用alarm 使用SIGALRM为connect设置超时 设置方法: ...

  7. SpringMVC的请求转发的三种方法

    SpringMVC请求转发的三种方法 首先明白请求转发是一次请求,地址栏不会发生变化,区别于重定向.springmvc环境自行配置. 以下举例中存在如下文件/WEB-INF/pages/success ...

  8. GET和POST是HTTP请求的两种基本方法,区别是什么!?

    GET和POST是HTTP请求的两种基本方法,要说它们的区别,接触过WEB开发的人都能说出一二. 最直观的区别就是GET把参数包含在URL中,POST通过request body传递参数. 你可能自己 ...

  9. ping请求超时的解决方法

    我们有时需要进行远程或者共享对方数据库的时候,会ping一下对方电脑,时候能够ping通,时候能够进行数据的传输.有时会出现ping请求超时,那么遇到这个问题该怎么解决? 我们首要解决的是看他自己是否 ...

随机推荐

  1. 用 Hystrix 构建高可用服务架构

    1 hystrix是什么 在分布式系统中,每个服务都可能会调用很多其他服务,被调用的那些服务就是依赖服务,有的时候某些依赖服务出现故障也是很正常的. Hystrix 可以让我们在分布式系统中对服务间的 ...

  2. HttpURLConnection发送GET、POST请求

    HttpURLConnection发送GET.POST请求 /** * GET请求 * * @param requestUrl 请求地址 * @return */ public String get( ...

  3. [转] 2018年最新桌面CPU性能排行天梯图(含至强处理器)

    [FROM] http://www.idn100.com/zuzhuangdiannaopeizhi-pc2849/ 排名 处理器 图例 分数 1 Intel Xeon Platinum 8173M ...

  4. 计算几何误差修正cmp

    //计算几何误差修正 Math.EPS=0.00000001; //判断x的符号 Math.cmp=function(x) { if(Math.abs(x)<Math.EPS)return 0; ...

  5. mysql数据库基本知识

    一.库操作 创建数据库:creat database 'mydababase1';creat database if not exists 'mydababase1'  //只有两个选项 查询数据库: ...

  6. redux设计到源码 --- 美团点评技术团队(转)

    https://tech.meituan.com/redux-design-code.html

  7. 阅读The Java® Language Specification需要知道的英文单词

      In any case/on any account  在任何情况下 “Varargs”是“variable number of arguments”的意思.有时候也被简单的称为“variable ...

  8. java.lang.IllegalArgumentException: Comparison method violates its general contract!

    这个错误就是写比较器的时候少写了返回值的情况: 比如: Collections.sort(list, new Ordering<QtmSysUserListDto>() { @Overri ...

  9. Velocity初始化过程解析

    velocity就是由template,engine,context组成. 1.首先创建一个template(如果是用在web上就是一个html文件),将需要参数化或实例化的地方用跟context有关 ...

  10. [中英对照]Booting Process in Linux RHEL 7 | Linux RHEL 7启动过程

    Booting Process in Linux RHEL 7 | Linux RHEL 7启动过程 In this post, I will guide you booting process in ...