2012-04-12 36 views
0

服务器关闭后,这段代码会不断地重复调用服务器,一旦请求失败,我怎么能让它停止重复调用?也许一个catch/error块?但我不知道如何实现它。谢谢!服务器关闭后,此代码段会不断调用服务器,如何停止?

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 = ... 
+0

某些代码缺失。此代码无法运行 – 2012-04-12 18:01:08

+0

此问题与JSP无关。标签已移除 – 2012-04-12 18:03:47

回答

0

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

它有助于使catch()块重新抛出错误吗?

e.printStackTrace(); 
throw e; 
0

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

我看这样的Java网络: 设置连接 - >发送连接请求 - >连接 - >获取数据 - >做一些数据 - >关闭连接

尽快HttpURLConnection.disconnect()快速注意,确保即使发生异常也会断开连接。如果您愿意,可以尝试在最后添加} finally {声明。