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. 【性能测试】:监控Mysql数据库方式

    1,  进入到/etc目录下,打开my.cnf文件,在文件最后添加几行 slow_query_log = ON                             //打开慢查询开关 slow_q ...

  2. LTE:EPC

    User Identifiers - IMSI and GUTI IMSI   A globle id that unique identifies a subscribe.It composed t ...

  3. pyserial timeout=1 || timeout=0.01

    昨天在做串口通信时候发现,串口参数(timeout=1 || timeout=0.01)对通信的读数据竟然影响很大,代码如下: self.ser = serial.Serial(port=serial ...

  4. mono 的System.Data.SqlClient小记录

    厦门-JuzzPig()  15:33:36System.Data.SqlClient 不科学的广州-PC286()  15:33:42webservice 返回的是 xml厦门-JuzzPig()  ...

  5. javascript绑定事件addEventListener与attachEvent

    1.eleObj.addEventListener(eventName,handle,useCapture); eleObj:DOM元素: eventName:事件名称.注意,这里的事件名称没有“ o ...

  6. hibernate关联关系的crud2

    hibernate关联关系的CRUD操作,解释都在注释里了,讲了fetchType.cascade. User类: package com.oracle.hibernate; import javax ...

  7. Linq to SharePoint与权限提升(转)

    转自http://www.cnblogs.com/kaneboy/archive/2012/01/25/2437086.html SharePoint 2010支持Linq to SharePoint ...

  8. Oracle执行计划的查看

    前言 一个系统在刚开始的时候,由于数据库中数据量不大,开发人员的主要精力都在业务与功能实现上.系统完成部署上线后随着时间的累积,每个表中的数据都在不断增长,我们往往会发现系统越来越慢,这可能是程序设计 ...

  9. 如何将本地文件通过终端上传到linux服务器或从linux主机下载文件到本地

    第一种方式: SecureCRT下上传文件只需在shell终端仿真器中输入命令“rz”,即可从弹出的对话框中选择本地磁盘上的文件,利用Zmodem上传到服务器当前路径下.下载文件只需在shell终端仿 ...

  10. 使用原生JavaScript实现对select增加option标签并附加value属性

    好久没有写原生的东西了,今天写了一个小项目里面包含着option选项,所以我决定使用原生JavaScript动态生成, 本着互联网分享精神,我将本篇文章分享给大家. html代码(就是一个select ...