0

一旦服务器关闭,这个片段就会不断地重复调用服务器,一旦请求失败,我怎样才能让它停止重复调用?也许是一个捕获/错误块?但我不确定如何实现它。谢谢!

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 = ...
4

2 回答 2

0

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

让你的 catch() 块重新抛出错误有帮助吗?

e.printStackTrace();
throw e;
于 2012-04-12T18:16:07.540 回答
0

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

我从 Java 的角度来看网络是这样的:设置连接 --> 发送连接请求 --> 已连接 --> 获取数据 --> 对数据进行操作 --> 关闭连接

就目前而言,请快速注意HttpURLConnection.disconnect(),确保即使抛出异常也会断开连接。} finally {如果您愿意,可以尝试在末尾添加语句。

于 2012-04-12T19:02:42.760 回答