Binary Data Over REST Web Service

There was requiremnet to retrieve images from a Content Management System and render the content to a portlet deployed in Liferay.

The application was built on top of Spring MVC portlet and the Service calls from Portlet was REST API calls. So the REST WS API was made to return a byte[] of the content

To sent binary data in REST call [senting binary over REST WS may be questioned], you should encode using sun.misc.BASE64Encoder and on the receiving end you can use sun.misc.BASE64Decoder to decode the data.

The code looks like this

Service API

@RequestMapping(value = "/cms/image", method = RequestMethod.GET)
public void (ModelMap modelMap){
byte[] buff= getBytes(); // Return the byte[] of the image
String
imgaeArray= new sun.misc.BASE64Encoder().encode(buff);
modelMap.addAttribute("result", imgaeArray);
}

At Portlet end;

@Autowired
RESTRepository repository;

@RequestMapping(params = "action=preview")
public String preview(Model model, RenderRequest renderRequest,RenderResponse renderResponse) {
Map <String, Object> paramMap = new HashMap
<String, Object>();
Map
<String, String> map = repository.get("/cms/image", Map.class,paramMap);
byte []
imgaeArray= new sun.misc.BASE64Decoder().decodeBuffer(map.get("result"));

}

If you don't know the content type, then you may need to return a DTO in the REST API instead of just encoded
byte[] . DTO can have the properties to hold the byte[] and the content type.

No comments:

Post a Comment