Search code examples
filejava-metransfer

web service - mobile application (j2me) file transfer


What i'm trying to do is transfer an image from the web service to the mobile client. In order to do this i've created a web service operation that returns a byte[] variable. In this method i create an .png image from a chart. After this i get the bytes from the image and provide them as a return value for the operation. this is the server code:

public byte[] getBytes() throws IOException { 

BufferedImage chartImage = chart.createBufferedImage(230, 260); 
//I get the image from a chart component. 
ByteArrayOutputStream baos = new ByteArrayOutputStream(1000); 


ImageIO.write( chartImage, "png",baos ); 


baos.flush(); 
byte[] bytesImage = baos.toByteArray(); 

baos.close(); 

return bytesImage; 
} 

Now in the mobile application all i do is assign a byte[] variable the return value of the web service operation.

byte[] imageBytes = Stub.getBytes().

Maybe i'm missing something but this is not working as i get this runtime error:

java.rmi.MarshalException: Expected Byte, received: iVBORw0KGgoAAAANSUhEU.... (very long line).

have any ideas why this happends? Or maybe you can suggest any other way to send the data to the mobile client.


Solution

  • If the service is only delivering an image as a byte array, the overhead induces by wrapping this in a SOAP response and XML/SOAP parsing on the client side seem rather unnecessary. Why don't you implement the chart generation in a servlet and let the client retrieve the image from a 'non-SOAP' server URL?

    Instead of returning bytesImage from a WebService method like you do, you could instead write the byte array to the servlet's response object:

    response.setContentType("image/png");
    response.setContentLength(bytesImage.length);
    OutputStream os = response.getOutputStream();
    os.write(bytesImage);
    os.close();
    

    On the J2ME client, you would read the response from the URL, to which the servlet is bound and create an image from the data:

    HttpConnection conn = (HttpConnection)Connector.open("http://<servlet-url>");
    DataInputStream dis = conn.openDataInputStream();
    byte[] buffer = new byte[conn.getLength()];
    dis.readFully(buffer);
    Image image = Image.createImage(buffer, 0, buffer.length);
    

    Hope this helps!