Wednesday, April 22, 2009

httpurlconnection 超时设置 (jdk1.4)

更多精彩请到 http://www.139ya.com


import java.util.*;
import java.net.*;
import java.io.*;
public class TimedUrlConnection implements Observer {
private URLConnection ucon = null;
private int time = 300000;//max time out
private boolean connected = false;
public TimedUrlConnection (URLConnection ucon,int time) {
this.ucon = ucon;
this.time = time;
}
public boolean connect() {
ObservableURLConnection ouc = new
ObservableURLConnection(ucon);
ouc.addObserver(this);
Thread ouct = new Thread(ouc);
ouct.start();
try {
ouct.join(time);
}
catch (InterruptedException i) {
//false, but should already be false
}
return(connected);
}
public void update(Observable o, Object arg) {
connected = true;
}//end of public void update(Observable o, Object arg)
}
class ObservableURLConnection extends Observable implements Runnable {
private URLConnection ucon;
public ObservableURLConnection(URLConnection ucon) {
this.ucon = ucon;
}//end of constructor
public void run() {
try {
ucon.connect();
setChanged();
notifyObservers();
}
catch (IOException e) {
}
}//end of public void run()
}



//~~~~~~~~~~~~~~~~~~~Usage~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
URL url=new URL(someurlname);
URLConnection urlconn=url.openConnection();
TimedUrlConnection timeoutconn=new TimedUrlConnection(urlconn,100000);//time out: 100seconds
boolean bconnectok=timeoutconn.connect();
if(bconnectok==false)
{
//urlconn fails to connect in 100seconds
}
else
{
//connect ok
}

http://topic.csdn.net/t/20010823/09/252141.html

(二)

HttpURLConnection中如何设置网络超时
2005年02月03日 益众网
作者:happy_fish


Java中可以使用HttpURLConnection来请求WEB资源。
HttpURLConnection对象不能直接构造,需要通过URL.openConnection()来获得HttpURLConnection对象,示例代码如下:
String szUrl = "http://www.ee2ee.com/";
URL url = new URL(szUrl);
HttpURLConnection urlCon = (HttpURLConnection)url.openConnection();

HttpURLConnection是基于HTTP协议的,其底层通过socket通信实现。如果不设置超时(timeout),在网络异常的情况下,可能会导致程序僵死而不继续往下执行。可以通过以下两个语句来设置相应的超时:
System.setProperty("sun.net.client.defaultConnectTimeout", 超时毫秒数字符串);
System.setProperty("sun.net.client.defaultReadTimeout", 超时毫秒数字符串);
其中: sun.net.client.defaultConnectTimeout:连接主机的超时时间(单位:毫秒)
sun.net.client.defaultReadTimeout:从主机读取数据的超时时间(单位:毫秒)

例如:
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
System.setProperty("sun.net.client.defaultReadTimeout", "30000");

JDK 1.5以前的版本,只能通过设置这两个系统属性来控制网络超时。在1.5中,还可以使用HttpURLConnection的父类URLConnection的以下两个方法:
setConnectTimeout:设置连接主机超时(单位:毫秒)
setReadTimeout:设置从主机读取数据超时(单位:毫秒)

例如:
HttpURLConnection urlCon = (HttpURLConnection)url.openConnection();
urlCon.setConnectTimeout(30000);
urlCon.setReadTimeout(30000);

需要注意的是,笔者在JDK1.4.2环境下,发现在设置了defaultReadTimeout的情况下,如果发生网络超时,HttpURLConnection会自动重新提交一次请求,出现一次请求调用,请求服务器两次的问题(Trouble)。

No comments: