在循环java中下载图像我

时间:2012-02-04 03:52:01

标签: java-me midp

在我的应用程序中,我们必须从服务器下载大约10张图像并在移动设备中显示。我怎样才能做到这一点?我可以使用相同的HttpConnection进行完整下载吗?还有其他的下载方式吗?

2 个答案:

答案 0 :(得分:1)

你可以用这个简单的循环(假设imageList是一个带有图像url的List)。

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();
       }
    }
}

答案 1 :(得分:-3)

您可以在循环中尝试使用以下方法从服务器下载图像。

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();
        }