2012-02-10 45 views
1

我有一個例程從https web服務獲取響應。第一次調用例程時,它可以很好地工作,返回我可以處理的xml。下一次調用它時,使用完全相同的參數,它將返回一個空文檔,稍後會導致錯誤。如果我再次調用例程,它就會起作用 - 事實上,它似乎每隔一次調用它時就會返回空文檔。我想也許我沒有正確關閉urlConnection,但它在代碼中看起來很好。第二遍urlConnection.getInputStream()返回空文檔

我能想到的唯一的另一件事是,從異步查詢中的postExecute事件調用例程。儘管如此,仍然只有一個查詢發生,所以沒有別的事情可以與之衝突。

代碼下面的例子:

private VEDResult LookupReg(String RegNo) 
{ 
    HttpURLConnection urlConnection = null; 
    InputStream in = null; 

    VEDResult VR = new VEDResult(); 

    try 
    {   

    // Create the URL 
    // 
    URL url = null; 
    url = new URL("https://<path>/getved.php?vrm=" + RegNo); 

    // Open the URL connection 
    // 
    urlConnection = (HttpURLConnection) url.openConnection(); 

    // Fetch the data from the server 
     // 
    in = new BufferedInputStream(urlConnection.getInputStream()); 

    // Set up document builder for creating the XML document 
    // 
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
    DocumentBuilder db; 
    db = dbf.newDocumentBuilder(); 

    // Create the XML document from the data we received 
    // 
    Document doc = db.parse(in); 
    doc.getDocumentElement().normalize(); 

    in.close(); 
    in = null; 

    // Get the individual nodes from the document and assign them to the result record 
    // 
    NodeList MakeNodes = doc.getElementsByTagName("MAKE"); 
    if (MakeNodes != null && MakeNodes.getLength() != 0) 
     VR.Make = MakeNodes.item(0).getTextContent(); 

    NodeList ModelNodes = doc.getElementsByTagName("MODEL"); 
    if (ModelNodes != null && ModelNodes.getLength() != 0) 
     VR.Model = ModelNodes.item(0).getTextContent(); 

    NodeList EmissionsNodes = doc.getElementsByTagName("CO2EMISSIONS"); 
    if (EmissionsNodes != null && EmissionsNodes.getLength() != 0) 
     VR.Emissions = EmissionsNodes.item(0).getTextContent(); 

    NodeList CostNodes = doc.getElementsByTagName("VED12MONTHS"); 
    if (CostNodes != null && CostNodes.getLength() != 0) 
     VR.Cost = CostNodes.item(0).getTextContent(); 

    NodeList RegNodes = doc.getElementsByTagName("VRM"); 
    if (RegNodes != null && RegNodes.getLength() != 0) 
     VR.RegNo = RegNodes.item(0).getTextContent(); 

    NodeList BandNodes = doc.getElementsByTagName("VEDBAND"); 
    if (BandNodes != null && BandNodes.getLength() != 0) 
     VR.VEDBand = BandNodes.item(0).getTextContent().toUpperCase(); 


    } 
    catch (Exception e) 
    { 
    Log.v("fs", e.toString()); 
    } 
    finally 
    { 
    // Tidy up 
    // 
    urlConnection.disconnect(); 
    urlConnection = null; 

    }  

    return VR; 
} 

回答

0

嘗試在每次通話後做垃圾回收。

System.runFinalization(); 
System.gc(); 
+0

剛剛試了一下 - 沒有喜悅恐怕仍然有同樣的問題... – Bermudabob 2012-02-10 11:02:23

0

之前打開的連接問題:

System.setProperty("http.keepAlive", "false"); 
相關問題