urlConnection.getInputStream()的第二次传递返回空文档

时间:2012-02-10 09:23:13

标签: android urlconnection

我有一个例程可以从https网络服务获得响应。第一次调用例程时,它完美地工作,返回我可以处理的xml。下次调用时,如果参数完全相同,则会返回一个空文档,以后会导致错误。如果我再次调用例程,它可以工作 - 实际上它似乎每隔一次调用它就会返回空文档。我想也许我没有正确关闭urlConnection,但它在代码中看起来还不错。

我能想到的另一件事是在异步查询中从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;
}

2 个答案:

答案 0 :(得分:0)

每次通话后尝试进行垃圾收集。

System.runFinalization();
System.gc();

答案 1 :(得分:0)

在您打开连接问题之前:

System.setProperty("http.keepAlive", "false");