3

I'm using Spring and Rest web service and I have a problem with byte array and String. I have to send a String in my ResponseEntity and on the client I have to retrieve the original String. I can't use ResponseEntity<String> because I need to send file. This is part of my web services that send String or file:

@Override
@RequestMapping(value = "/file", method = RequestMethod.GET) 
    public  ResponseEntity<byte[]> getAcquisition(HttpServletResponse resp,@RequestParam(value="filePath", required = true) String filePath){
        final HttpHeaders headers = new HttpHeaders();
        OutputStream outputStream = null;
        File toServeUp= null;
        try{
            toServeUp=new File(filePath);
            if (!toServeUp.exists()){
                headers.setContentType(MediaType.TEXT_PLAIN);
                LOG.error("Threw exception in MatlabClientControllerImpl::getAcquisition : File doesn't exists!!");
                String message = "ERROR: Could not retrieve file on server, check the path!";       
                return new ResponseEntity<byte[]>(message.getBytes(("UTF-8")), headers, HttpStatus.OK);
.....

On the client I use this method:

@Override
    public Response getFile(String serverIp, String toStorePath, String filePath){
        ResponseEntity<byte[]> responseEntity = null;
        try{
            RestTemplate restTemplate = new RestTemplate();
            responseEntity  = restTemplate.getForEntity(serverIp + "ATS/client/file/?filePath={filePath}", byte[].class, filePath); 

            if (MediaType.TEXT_PLAIN.toString().equals(responseEntity.getHeaders().getContentType().toString()))
                return new Response(false, false, new String(responseEntity.getBody(),"UTF-8"), null);
....

This is an example of response:

{
  "status": false,
  "success": false,
  "result": "IlJWSlNUMUk2SUVWeWNtOXlJR2x1SUhSb1pTQndZWFJvTENCamFHVmpheUJwZENFPSI=",
  "error": null
}

But I retrieve several characters but not those I had sent through the server. I have tried a lot of alternatives but none works. Do you have any idea? Thanks

alexbt
  • 16,415
  • 6
  • 78
  • 87
luca
  • 3,248
  • 10
  • 66
  • 145
  • Did you tried? http://stackoverflow.com/questions/12239868/whats-the-correct-way-to-send-a-file-from-rest-web-service-to-client – praful prajapati Dec 14 '15 at 09:44
  • Yes, I saw it. I spent about three day to find one code that works with download and upload file and ResponseEntity allow it. Response is a my class not the default 'Response' – luca Dec 14 '15 at 09:47
  • 1
    Usually it would be like files bytes converted to base64. Did you try decoding from base64 and write those bytes in file and check contents. – Himanshu Bhardwaj Dec 14 '15 at 10:41
  • If I use new String(Base64.decodeBase64(responseEntity.getBody()),Charset.forName("UTF-8")) it works. Many thanks. Add The response so I can set as true – luca Dec 14 '15 at 13:39

0 Answers0