1

我在黑莓应用程序中获取数据时遇到问题。下面的代码我用来从 xml 格式的服务器获取数据并解析这些数据并将其显示给用户。它在 wi-fi 中工作正常但是当我运行时它在使用 EDGE 或 GPRS 的真实设备上运行非常缓慢,而且很多时候它使输入流为空。我不明白为什么会在慢速网络中发生这种情况,但在 wi-fi 中却没有。

public InputStream getInputStream(String url)
{   
    HttpConnection  httpConnection = null;
    try
    {
        httpConnection = getConnectionForRequest(url);
        final int iResponseCode = httpConnection.getResponseCode();
        if(iResponseCode == HttpConnection.HTTP_OK)
        {
            return httpConnection.openInputStream();

        }
        else
            return null;
    }
    catch (Exception e)
    {
        return null;
    }
            finally
            {
                if(httpConnection!=null)
                {
                      httpConnection.close();
                }
            }

}

public HttpConnection getConnectionForRequest(String url) 
{

    int[] availableTransportTypes = {TransportInfo.TRANSPORT_TCP_WIFI,
                                     TransportInfo.TRANSPORT_BIS_B, 
                                     TransportInfo.TRANSPORT_WAP2,
                                     TransportInfo.TRANSPORT_TCP_CELLULAR, 
                                     TransportInfo.TRANSPORT_MDS, 
                                     TransportInfo.TRANSPORT_WAP};
    final ConnectionFactory connectionFactory = new ConnectionFactory();


    for (int i = 0; i < availableTransportTypes.length; i++) 
    {
        int transport = availableTransportTypes[i];
        if (!TransportInfo.isTransportTypeAvailable(transport) || !TransportInfo.hasSufficientCoverage(transport)) 
        {
            Arrays.removeAt(availableTransportTypes, i);
        }
    }

    connectionFactory.setPreferredTransportTypes(availableTransportTypes);
    connectionFactory.setAttemptsLimit(50);
    connectionFactory.setConnectionTimeout(3000);
    connectionFactory.setTimeLimit(20000);
    final ConnectionDescriptor connectionDescriptor = connectionFactory.getConnection(url);
    HttpConnection connection = null;
    if (connectionDescriptor != null) 
    {
        connection = (HttpConnection) connectionDescriptor.getConnection();
    }

    return connection;
}


public boolean parseData()
{   
    InputStream  is = getInputStream("http://data.****.com/getData.aspx");
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder;
    Document doc;
    try 
    {
        docBuilder = docBuilderFactory.newDocumentBuilder();
        doc = docBuilder.parse(is);
        is.close();
        doc.getDocumentElement().normalize();
        docBuilder.isValidating();
    } 
    catch(Exception ex) 
    {           
        return false;
    }                                   
    return true;
}
4

0 回答 0