Sunday 26 April 2009

Using HttPClient to invoke a web service

Assume that the web service operation accepts a zip file as a base64 encoded string in its SOAP message body. Here is a way how I got it to work using commons HttpClient.



import org.apache.commons.io.FileUtils;
import org.apache.commons.httpclient.*;
import org.apache.commons.codec.binary.Base64;
import javax.xml.soap.*

public class FileUploader{


public static void main(String args[]) throws Exception{
String serviceEndpointUrl;// assign the service endpoint url here
File uploadingFile=new File("HelloWorld.zip");
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(serviceEndpointUrl);

RequestEntity re= getRequestEntity(uploadingFile)
method.setRequestEntity(re);

method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(1, false));

int statusCode = client.executeMethod(method);

String responseBody = method.getResponseBodyAsString();
System.out.println(responseBody);
}


static RequestEntity getRequestEntity(File file) throws Exception{
MessageFactory mFactory = MessageFactory.newInstance();
SOAPMessage message= mFactory.createMessage();
SOAPBody body= message.getSOAPBody();
SOAPElement zipElement=body.addChildElement("zip");

StringBuilder content= new StringBuilder();
byte[] arr= FileUtils.readFileToByteArray(file);
byte[] encoded= Base64.encodeBase64Chunked(arr);

for (int i= 0; i < encoded.length; i++) {
content.append((char) encoded[i]);
}

ByteArrayOutputStream b= new ByteArrayOutputStream();
message.writeTo(b);
String base64EncodedString= b.toString();

return new StringEntity(base64EncodedString);
}



You will need Apache commons jars in your classpath.

No comments: