代理。思考过程。我怎么能杀了他们?

时间:2012-08-28 00:37:16

标签: java exception proxy bufferedreader

有些时候通过代理服务器工作并读取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();

我试图使用反击但它不起作用......我可以用什么例外来控制这种情况?

1 个答案:

答案 0 :(得分:1)

您需要使用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