Binary Data In SOAP Web Service

Besides the text data type, web services is also able to handle the binary data type. With the ability to handle binary data, a web service is able to transfer image files to the client applications. What makes web service can transfer binary data is base64 encoding. Base64 can encode binary data into 64 characters (A to Z, a to z, 0 to 9, +, and /) so it can be included in SOAP document. What the client application need to do is just decode it back to binary data.

Implementation In NuSOAP

For the implementation, we're going to create a web service with PHP using NuSOAP as the supporting libraries. This web service has one method which will return a struct containing the detail of a book including its cover. The detail of the book such as title, author, publisher, and price are in text format. And, the cover is in binary format because it is an image file.

Before creating the application code, please create this table first and insert it with some records.

CREATE TABLE IF NOT EXISTS `book` (
  `id` int(5) NOT NULL AUTO_INCREMENT,
  `title` varchar(50) DEFAULT NULL,
  `author` varchar(50) DEFAULT NULL,
  `publisher` varchar(30) DEFAULT NULL,
  `price` bigint(6) DEFAULT NULL,
  `cover` varchar(20) DEFAULT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
 
INSERT INTO `book` (`id`, `title`, `author`, `publisher`, `price`, `cover`)
VALUES
(1, 'Book 1', 'Author 1', 'Publisher 1', 20, 'cover1.jpg'),
(2, 'Book 2', 'Author 2', 'Publisher 2', 15, 'cover2.jpg'),
(3, 'Book 3', 'Author 3', 'Publisher 3', 18, 'cover3.jpg');

And this is the code for the web service.


<?php
function getBookInfo($bookId){
    
mysql_connect("localhost","root","");
    
mysql_select_db("db1");

    

$result=mysql_query("SELECT * FROM book WHERE
                id='"
.mysql_escape_string($bookId)."'");

    if(

$data=mysql_fetch_array($result)){
        
// The location of the image files
        
$file="/var/www/webservices/images/".$data['cover'];
        
// The image file should exist
        
if(file_exists($file)){
            
$fh=fopen($file,"r");
            
$str=fread($fhfilesize($file));
            
fclose($fh);
        }
        else{
            
$str="";
        }
        
        
$book=array(
            
"id"=>$data['id'],
            
"title"=>$data['title'],
            
"author"=>$data['author'],
            
"publisher"=>$data['publisher'],
            
"price"=>$data['price'],
            
// Encode the file content to base64
            
"cover"=>base64_encode($str)
        );
    }

    

mysql_close();

    return 

$book;
}

//Include the NuSOAP main file
require("lib/nusoap.php");

$server=new soap_server();

$server->configureWSDL("Book","urn:BookService");

// Define the struct data type
$server->wsdl->addComplexType(
    
"book",
    
"complexType",
    
"struct",
    
"all",
    
"",
    array(
        
"id"=>array("name"=>"id","type"=>"xsd:string"),
        
"title"=>array("name"=>"title","type"=>"xsd:string"),
        
"author"=>array("name"=>"author","type"=>"xsd:string"),
        
"publisher"=>array("name"=>"publisher","type"=>"xsd:string"),
        
"price"=>array("name"=>"price","type"=>"xsd:long"),
        
// Base64 as the data type
        
"cover"=>array("name"=>"cover","type"=>"xsd:base64")
    )
);

// Registering the method
$server->register(
    
"getBookInfo",
    array(
"bookId"=>"xsd:string"),
    array(
"return"=>"tns:book"),
    
"urn:BookService",
    
"urn:BookService#getBookInfo"
);

$HTTP_RAW_POST_DATA=isset($HTTP_RAW_POST_DATA)? $HTTP_RAW_POST_DATA "";

$server->service($HTTP_RAW_POST_DATA);
?>
The Mobile Client Application

We have created the web service. Now, we will create a mobile application as the client. We will create it with Java and use Wingfoot SOAP as the supporting library.

Wingfoot SOAP came in ZIP file, so, you need to extract it first. After you extract it, you can copy the kvmwsoap_1.06.jar to the lib folder inside your project folder. By doing this, the Wingfoot SOAP library will be included in your project.

In this application, we just need to input the ID of book. If the ID was found, then the information of the book will be displayed including its cover. This is the code for our mobile application.

import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import com.wingfoot.soap.*;
import com.wingfoot.soap.encoding.*;
import com.wingfoot.soap.transport.*;
 
public class binaryFilesClient extends MIDlet implements CommandListener, Runnable{
    private Form form;
    private TextField txtBookId;
    private StringItem strMessage;
    private StringItem strId;
    private StringItem strTitle;
    private StringItem strAuthor;
    private StringItem strPublisher;
    private StringItem strPrice;
    private StringItem strCover;
    private Image img;
    private Command cmdOk;
    private Command cmdExit;
    private Display display;
    private boolean imageLoaded;
 
    public binaryFilesClient(){
        imageLoaded=false;
 
        form=new Form("Binary Files");
 
        txtBookId=new TextField("Book ID","",10,TextField.ANY);
 
        strMessage=new StringItem("","");
        strMessage.setPreferredSize(form.getWidth(),-1);
 
        strId=new StringItem("Book ID : ","");
        strId.setPreferredSize(form.getWidth(),-1);
 
        strTitle=new StringItem("Title : ","");
        strTitle.setPreferredSize(form.getWidth(),-1);
 
        strAuthor=new StringItem("Author : ","");
        strAuthor.setPreferredSize(form.getWidth(),-1);
 
        strPublisher=new StringItem("Publisher : ","");
        strPublisher.setPreferredSize(form.getWidth(),-1);
 
        strPrice=new StringItem("Price : ","");
        strPrice.setPreferredSize(form.getWidth(),-1);
 
        strCover=new StringItem("Cover : ","");
        strCover.setPreferredSize(form.getWidth(),-1);
 
        cmdOk=new Command("Ok",Command.OK,1);
 
        cmdExit=new Command("Exit",Command.EXIT,2);
 
        form.append(txtBookId);
        form.append(strMessage);
        form.append(strId);
        form.append(strTitle);
        form.append(strAuthor);
        form.append(strPublisher);
        form.append(strPrice);
        form.append(strCover);
        form.addCommand(cmdOk);
        form.addCommand(cmdExit);
        form.setCommandListener(this);
    }
 
    public void startApp(){
        display=Display.getDisplay(this);
        display.setCurrent(form);
    }
 
    public void pauseApp(){
    }
 
    public void destroyApp(boolean unc){
    }
 
    public void commandAction(Command c, Displayable d){
        if(c==cmdOk){
            new Thread(this).start();
        }
        if(c==cmdExit){
            destroyApp(false);
            notifyDestroyed();
        }
    }
 
    public void run(){
        try{
            // The location of web service
            String url="http://localhost/webservices/binaryfiles.php";
 
            Call c=new Call();
 
            // Set method name and its parameter
            c.setMethodName("getBookInfo");
            c.addParameter("bookId",txtBookId.getString());
 
            HTTPTransport transport=new HTTPTransport(url,null);
            transport.getResponse(true);
 
            Envelope res=c.invoke(transport);
 
            UntypedObject uo=(UntypedObject)res.getParameter(0);
 
            // If book found
            if(uo!=null){
                // Show the book information
                strMessage.setText("");
                strId.setText(uo.getPropertyValue(0).toString());
                strTitle.setText(uo.getPropertyValue(1).toString());
                strAuthor.setText(uo.getPropertyValue(2).toString());
                strPublisher.setText(uo.getPropertyValue(3).toString());
                strPrice.setText(uo.getPropertyValue(4).toString());
 
                // Display the book cover
                // Create base64 object base on the returned base64 string
                Base64 b=new Base64(uo.getPropertyValue(5).toString());
 
                // Create the image
                img=Image.createImage(b.getBytes(), 0, b.getBytes().length);
 
                // If image has been loaded, delete it first
                if(imageLoaded==true){
                    form.delete(form.size()-1);
                }
 
                // Append the image to form
                form.append(img);
 
                // Tell the application that the image has been loaded
                imageLoaded=true;
            }
            else{
                // Clear the information
                strMessage.setText("Book not found!");
                strId.setText("");
                strTitle.setText("");
                strAuthor.setText("");
                strPublisher.setText("");
                strPrice.setText("");
 
                // Clear the book cover
                // If image has been loaded, delete it
                if(imageLoaded==true){
                    form.delete(form.size()-1);
                }
            }
        }
        catch(Exception ex){
            strMessage.setText(ex.toString());
        }
    }
}

This is the screenshot of this mobile application when running.

binary data in wingfoot soap

Comments

Thanks you very much.
can you help me a problem?
- I write a web service in php language to recevie image data from C# application client.
-How to convert base64 encode to image data again in C# application?
Thank for your help.
:)

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <b> <i> <img> <span>
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <drupal6>, <java>, <javascript>, <php>, <python>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.