You can download an image from a web server using javax.microedition.io.HttpConnection in J2ME.

The folowing methods shows you how to do this. getImageFromUrl(...) method gets an url as a parameter and returns an javax.microedition.lcdui.Image. This is done with the help of getDataFromUrl(...) method.

 
  public static Image getImageFromUrl(String url) {
        Image img = null;
        
        try
        {            
          String imageData = getDataFromUrl(url);
          img = Image.createImage(imageData.getBytes(), 0, 
    imageData.length() );          
        }
        catch(Exception e1) {
            e1.printStackTrace();
        }
        
        return img;
    }

    public static String getDataFromUrl(String url) 
          throws IOException {

        StringBuffer b = new StringBuffer();
        InputStream is = null;
        HttpConnection c = null;
        
        long len = 0 ;
        int ch = 0;
        c = (HttpConnection)Connector.open(url);
        is = c.openInputStream();
        len = c.getLength();
        if( len != -1) {
            // Read exactly Content-Length bytes
            for(int i =0 ; i < len ; i++ )
                if((ch = is.read()) != -1) {
                b.append((char) ch);
                }
        } else {
            //Read until the connection is closed.
            while ((ch = is.read()) != -1) {
                len = is.available() ;
                b.append((char)ch);
            }
        }
        
        is.close();
        c.close();
        return b.toString();
    }  

 


 

 

 Related Tips