在我的应用程序中,我们必须从服务器下载大约10个图像,并在手机中显示。我该怎么做?我可以使用相同的HttpConnection进行完全下载吗?有其他下载方式吗?
您可以使用这个简单的循环(假设imageList是一个带有图像url的列表)。
HttpConnection = null;
Image image = null;
for (int i = 0; i < imageList.getSize(); i++) {
try{
String urlImage = imageList.get(i);
hc = (HttpConnection) Connector.open(urlImage);
image = Image.createImage(hc.openInputStream()));
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
hc.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
您可以在从服务器下载图像的循环中尝试以下方法。
private void downloadImage ( String URL )
{
try
{
System.out.println("URL FOR POST_DATA : "+URL);
// Open up a http connection with the Web server for both send and receive operations
httpConnection = (HttpConnection)Connector.open(URL, Connector.READ_WRITE);
// Set the request method to POST
httpConnection.setRequestMethod(HttpConnection.POST);
// Set the request headers
httpConnection.setRequestProperty(ConstantCodes.ACTION_MODE_PARAMETER,action);
httpConnection.setRequestProperty(ConstantCodes.USER_NAME_REQUEST_PARAMETER,userName);
if(eventName==null || eventName.equals(""))
eventName="default";
httpConnection.setRequestProperty(ConstantCodes.EVENT_NAME_REQUEST_PARAMETER, eventName);
httpConnection.setRequestProperty(ConstantCodes.CAMERAID_REQUEST_PARAMETER, cameraID);
// all the headers are sending now and connection chanel is establising
dis = httpConnection.openDataInputStream();
int ch = 0;
ByteArrayOutputStream bytearray = new ByteArrayOutputStream(250000);
while((ch = dis.read()) != -1)
bytearray.write(ch);
// fileByte contains whole file in bytes
byte fileByte[] = bytearray.toByteArray();
fileSize = fileByte.length;
System.out.println("Got file size : "+fileSize);
if(bytearray!=null) bytearray.close();
midlet.getLastPostedImageResponse(fileByte);
}
catch (IOException ioe)
{
ioe.printStackTrace();
System.out.println("IOException occured during getting last image data : "+ioe.getMessage());
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("Eeception occurred during getting last image data : "+e.getMessage());
}
finally
{
System.out.println("Calling close from Last image posted Action");
close();
}