日期:2014-05-20  浏览次数:20902 次

连接超时问题,完美解决再开帖给50分!!!!
小弟写了个下载网页的小程序,但是碰到某些速度很慢的网站就会报错:
java.net.ConnectException:   Connection   timed   out:   connect
at   java.net.PlainSocketImpl.socketConnect(Native   Method)
at   java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:305)
at   java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:171)
at   java.net.PlainSocketImpl.connect(PlainSocketImpl.java:158)
at   java.net.Socket.connect(Socket.java:452)
at   java.net.Socket.connect(Socket.java:402)
at   sun.net.NetworkClient.doConnect(NetworkClient.java:139)
at   sun.net.www.http.HttpClient.openServer(HttpClient.java:402)
at   sun.net.www.http.HttpClient.openServer(HttpClient.java:618)
at   sun.net.www.http.HttpClient. <init> (HttpClient.java:306)
at   sun.net.www.http.HttpClient. <init> (HttpClient.java:267)
at   sun.net.www.http.HttpClient.New(HttpClient.java:339)
at   sun.net.www.http.HttpClient.New(HttpClient.java:320)
at   sun.net.www.http.HttpClient.New(HttpClient.java:315)
at   sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:521)
at   sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:498)
at   search.PageMonitor.downloadPage(PageMonitor.java:147)
at   search.PageMonitor.set(PageMonitor.java:70)
at   search.PageMonitor.search(PageMonitor.java:283)
at   search.PageMonitor.run(PageMonitor.java:81)

出错的代码:
HttpURLConnection   con   =   (HttpURLConnection)url.openConnection();
con.connect();
BufferedReader   reader   =   new   BufferedReader(new   InputStreamReader(con.getInputStream(),   encoding));
String   line;
StringBuffer   pageBuffer   =   new   StringBuffer();
while   ((line   =   reader.readLine())   !=   null)   {
        pageBuffer.append(line   +   "\n ");
}

小弟想延长url的连接超时时间,但是不知道怎么弄?或者那位大哥有更好的办法?

------解决方案--------------------
con.setConnectTimeout(30000);
------解决方案--------------------
查查帮助文档吧!
看看这个方法行不行setConnectTimeout(int timeout)//当参数为0时,表示无穷大超时。
------解决方案--------------------
确实,setConnectionTimeout标记了 since 1.5~~~

MARK~


------解决方案--------------------
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 ");

------解决方案--------------------
也可以用httpclient
http://www.innovation.ch/java/HTTPClient/
------解决方案--------------------