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();
}
}

最新文章

  1. 窗体Showmedol 遇到的奇怪异常: cannot make a visible window model
  2. node.js grunt文件压缩
  3. DotNetBar for Windows Forms 11.8.0.8冰河之刃重打包版
  4. Bat脚本实现MySQL数据库SQL文件备份
  5. Java 读取Properties配置文件
  6. 入侵检测课设之Libnids开发包
  7. hdu 1541/poj 2352:Stars(树状数组,经典题)
  8. [html] HTML结构的语义化
  9. Java基础知识强化之网络编程笔记24:Android网络通信之 AndroidAsync(基于nio的异步通信库)
  10. 人工智能-有限状态机(FSM)的学习
  11. winform调用WCF默认实例
  12. css案例学习之盒子模型
  13. IP选路
  14. python3 annotations
  15. [BZOJ]1019 汉诺塔(SHOI2008)
  16. PostgreSQL安装详细步骤windows
  17. pip使用国内源
  18. ionic3使用第三方图标
  19. Mysql 主键常用修改
  20. MVC 中文显示乱码问题

热门文章

  1. Python【每日一问】17
  2. (六)Audio子系统之AudioRecord.release
  3. (转)CentOS7.4环境下搭建--Gluster分布式集群存储
  4. Java中的语法树结构
  5. Android AES加密工具类实现(基础回顾)
  6. python-Event事件线程同步和互斥
  7. 微服务Kong(四)——添加插件
  8. spring data 自定义接口
  9. 得到DataGrid列的值
  10. [PY3]——基本语法