首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >代理服务器。思考过程。我怎么才能杀了他们?

代理服务器。思考过程。我怎么才能杀了他们?
EN

Stack Overflow用户
提问于 2012-08-28 08:37:16
回答 1查看 163关注 0票数 0

有时工作通过代理服务器和读取prom缓冲区的内容,我的程序认为,所以更多的时间…直到我把它们合上。如何设置从几秒钟开始的程序代码,如果没有来自服务器的任何应答,则采取另一个服务器?

代码语言:javascript
复制
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();

我试着使用计数器,但它不起作用...我可以使用什么异常来通过我的控制来捕捉这种情况?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-08-28 09:17:25

您需要使用URLConnection.setReadTimeout。从规范来看,

将读取超时设置为指定的超时,以毫秒为单位。非零值指定在与资源建立连接时从输入流读取时的超时时间。如果在有数据可供读取之前超时,则会引发java.net.SocketTimeoutException。零的超时被解释为无限超时。

如你所见,读取超时将抛出SocketTimeoutException,你可以适当地捕获它,例如

代码语言:javascript
复制
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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12151370

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档