首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >一旦服务器宕机,这段代码就一直在重复调用服务器,该如何停止?

一旦服务器宕机,这段代码就一直在重复调用服务器,该如何停止?
EN

Stack Overflow用户
提问于 2012-04-13 01:58:21
回答 2查看 44关注 0票数 0

一旦服务器宕机,这段代码就一直在重复调用服务器,一旦请求失败,我如何让它停止重复调用呢?也许是一个catch/error块?但我不确定如何实现它。谢谢!

代码语言:javascript
复制
HttpURLConnection httpConn = null;
InputStream is = null;
OutputStream os = null;
String xmlResponse = null;

try {
   //Open Connection

       String CollectionId="123";
       String GetHTML="1";

       String urlString = "http://tester.com/webservices/ContentWS.asmx/GetCollection?CollectionId="+CollectionId+"&GetHTML="+GetHTML;

       System.out.println(urlString);

       //String encodedUrl = URLEncoder.encode(urlString,"UTF-8");

   URL url = new URL(urlString);
   httpConn = (HttpURLConnection)url.openConnection();

   //Setup Request
   httpConn.setRequestMethod("GET");
   httpConn.setDoOutput(true);
   httpConn.setReadTimeout(10000);
   httpConn.connect();

   xmlResponse = convertStreamToString(httpConn.getInputStream());
  }
  catch (IOException e) {
      e.printStackTrace();
   }

String htmlContent = "";
   try {
       DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
       DocumentBuilder db = dbf.newDocumentBuilder();
       InputSource input = new InputSource();
       input.setCharacterStream(new StringReader(xmlResponse));

       Document doc = db.parse(input);
       NodeList nodes = doc.getElementsByTagName("Item");

       // iterate the Items
               int i = 0;
               int j = 0;
               Date now = new Date();
       for (i = 0; i < 2; i++) {
                  //Grab HTML to append to htmlContent
                  NodeList teaser = doc.getElementsByTagName("Html");
                  Element line = (Element) teaser.item(i);
                  htmlContent += getCharacterDataFromElement(line);
       }
   }
   catch (Exception e) {
       e.printStackTrace();
   }
htmlContent = ...
EN

回答 2

Stack Overflow用户

发布于 2012-04-13 02:16:08

这段代码打印堆栈跟踪,但不抛出错误,因此您的调用代码不知道这个问题。

让catch()代码块重新抛出错误是否有帮助?

代码语言:javascript
复制
e.printStackTrace();
throw e;
票数 0
EN

Stack Overflow用户

发布于 2012-04-13 03:02:43

一切似乎都很好用。您的连接已打开并正常工作,但您忘记了一个小细节。完成后,您必须使用HttpURLConnection.disconnect()来告诉程序您已经完成了从连接请求信息。

我从Java的角度看待网络是这样的:建立连接-->发送连接请求-->连接-->获取数据-->对数据做一些事情-->关闭连接

HttpURLConnection.disconnect()而言,需要注意的是,即使抛出异常,它也会断开连接。如果愿意,您可以尝试在末尾添加} finally {语句。

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

https://stackoverflow.com/questions/10129107

复制
相关文章

相似问题

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