Monday, March 14, 2011

XML binary attachments java sample(Hello World)

I want to send a binary file on the Internet using webservice xml attachment. I am looking for how to attach a binary file in xml on the net. I found lots of them. However, non of them I like.

I decided to write my own.
Webservice is using http protocol - text-based protocol. To send binary file on the net, we can simply convert binary code to text and 64bit encode it. Once you receive it, 64bit-decode it and convert it back to binary.
Here is sample:

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.codec.binary.Base64;

public class Test {

/**
* @param args
*/
public static void main(String[] args) throws Exception {

//Before sending
File file = new File("C:\\temp\\helloworld.tif");
byte binaryData[] = loadFile(file);
String encodedString = Base64.encodeBase64String(binaryData);
System.out.println(encodedString);

// Sending following
//"<attachment>"+encodedString+"</attachment>"

//Receiving it an save it to file
byte binaryData2[] = Base64.decodeBase64(encodedString);
writeToFile("c:\\temp\\helloworld2.tif", binaryData2);

}

private static void copy(InputStream in, OutputStream out) throws IOException {
byte[] barr = new byte[1024];
while(true) {
int r = in.read(barr);
if(r <= 0) {
break;
}
out.write(barr, 0, r);
}
}

private static byte[] loadFile(File file) throws IOException {
InputStream in = new FileInputStream(file);
try {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
copy(in, buffer);
return buffer.toByteArray();
} finally {
in.close();
}
}

private static void writeToFile(String filePath, byte[] data) throws Exception {
//byte data[] = {1, 2, 3, 4};

FileOutputStream fileoutputstream = new FileOutputStream(filePath);

for (int i = 0; i < data.length; i++) {
fileoutputstream.write(data[i]);
}

fileoutputstream.close();
}


}

You need Apache commons-codec jar file. You can get it from http://commons.apache.org/codec/

More tutorials: http://jsptutorblog.blogspot.com/