我在使用blackberry应用程序获取数据时遇到问题。我使用的代码来自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;
}