有时工作通过代理服务器和读取prom缓冲区的内容,我的程序认为,所以更多的时间…直到我把它们合上。如何设置从几秒钟开始的程序代码,如果没有来自服务器的任何应答,则采取另一个服务器?
URL url = new URL(linkCar);
String your_proxy_host = new String(proxys.getValueAt(xProxy, 1).toString());
int your_proxy_port = Integer.parseInt(proxys.getValueAt(xProxy, 2).toString());
Proxy proxy = null;
// System.out.println(proxys.getValueAt(xProxy, 3).toString());
// if (proxys.getValueAt(xProxy, 3).toString().indexOf("HTTP") > 0)
// {
proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(your_proxy_host, your_proxy_port));
// } else {
// proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(your_proxy_host, your_proxy_port));
// }
HttpURLConnection connection = (HttpURLConnection)url.openConnection(proxy);
connection.setConnectTimeout(1000);
connection.connect();
String line = null;
StringBuffer buffer_page = new StringBuffer();
BufferedReader buffer_input = new BufferedReader(new InputStreamReader(connection.getInputStream(),"cp1251"));
int cc = 0;
//this is thinking place!!!
while ((line = buffer_input.readLine()) != null && cc < 7000) {
buffer_page.append(line);
cc++;
}
doc = Jsoup.parse(String.valueOf(buffer_page));
connection.disconnect();我试着使用计数器,但它不起作用...我可以使用什么异常来通过我的控制来捕捉这种情况?
发布于 2012-08-28 09:17:25
您需要使用URLConnection.setReadTimeout。从规范来看,
将读取超时设置为指定的超时,以毫秒为单位。非零值指定在与资源建立连接时从输入流读取时的超时时间。如果在有数据可供读取之前超时,则会引发java.net.SocketTimeoutException。零的超时被解释为无限超时。
如你所见,读取超时将抛出SocketTimeoutException,你可以适当地捕获它,例如
try (BufferedReader buffer_input = new BufferedReader(
new InputStreamReader(connection.getInputStream(), "cp1251"))) {
String line;
while ((line = buffer_input.readLine()) != null) {
buffer_page.append(line);
}
} catch (SocketTimeoutException ex) {
/* handle time-out */
}请注意,在如上使用readLine时需要小心--这将从输入中剥离所有的\r和\n。
https://stackoverflow.com/questions/12151370
复制相似问题