【发布时间】:2012-06-30 00:49:10
【问题描述】:
在我的应用程序中,我需要从服务器下载多个图像。我使用此代码获取字节数组:
HttpConnection connection = null;
InputStream inputStream = null;
byte[] data = null;
try
{
//connection = (HttpConnection)Connector.open(url);
connection = (HttpConnection)Connector.open(url, Connector.READ_WRITE, true);
int responseCode = connection.getResponseCode();
if(responseCode == HttpConnection.HTTP_OK)
{
inputStream = connection.openInputStream();
data = IOUtilities.streamToBytes(inputStream);
inputStream.close();
}
connection.close();
return data;
}
catch(IOException e)
{
return null;
}
网址由后缀“;deviceSide=false;ConnectionType=MDS - public”(不带空格)组成,并且运行良好。
问题在于,如果手机没有 SIM 卡,我们无法通过 MDS 服务器连接到互联网。所以我们改用连接工厂,让BB随便选:
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection(url);
if (connDesc != null)
{
final HttpConnection httpConn;
httpConn = (HttpConnection)connDesc.getConnection();
try
{
httpConn.setRequestMethod(HttpConnection.GET);
final int iResponseCode = httpConn.getResponseCode();
if(iResponseCode == HttpConnection.HTTP_OK)
{
InputStream inputStream = null;
try{
inputStream = httpConn.openInputStream();
byte[] data = IOUtilities.streamToBytes(inputStream);
return data;
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
finally{
try
{
inputStream.close();
} catch (IOException e)
{
e.printStackTrace();
return null;
}
}
}
}
catch (IOException e)
{
System.err.println("Caught IOException: " + e.getMessage());
}
}
return null;
连接有效,因为它选择了好的前缀(在我们的例子中为 interface=wifi),但这会产生另一个问题。
有些图像没有很好地下载,其中一些(每次尝试都不相同)已损坏,但仅当手机使用 wifi 连接来获取这些图像时。
如何避免这个问题?我必须使用什么方法来获得连接?是否可以检查用户是否有 SIM 卡才能使用 MDS - public ?
这是一个损坏图像的示例:
error image http://nsa30.casimages.com/img/2012/06/28/120628033716123822.png
【问题讨论】:
标签: image blackberry httpconnection corrupt