1

in my Spring Rest web service I send a file (even big size) as byte array but when I receive the information, the object is a String so when I make the cast from Object to byte[] I receive the following error:

java.lang.ClassCastException: java.lang.String cannot be cast to [B

The originl file is converted through

Files.readAllBytes(Paths.get(path))

and this byte[] is filled in one object with a field result of Object type. When the Client retrieve this object and it gets result class with cast to byte[] it appears the above exception, this is the client code

Files.write(Paths.get("test.txt"),((byte[])response.getResult()));

If I use a cast to string and then to bytes the content of the file is different from original file. I don't care the file type, file content, I only have to copy from server to client directory How can I do?Thanks

server class:

@Override
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public @ResponseBody Response getAcquisition(@RequestParam(value="path", defaultValue="/home") String path){
        try {
            byte[] file = matlabClientServices.getFile(path);
            if (file!=null){
                FileTransfer fileTransfer= new FileTransfer(file, Paths.get(path).getFileName().toString());
                return new Response(true, true, fileTransfer, null);
            }
            else 
                return new Response(false, false, "File doesn't exist!", null);         
        } catch (Exception e) {
            ErrorResponse errorResponse= ErrorResponseBuilder.buildErrorResponse(e);
            LOG.error("Threw exception in MatlabClientControllerImpl::getAcquisition :" + errorResponse.getStacktrace());
            return new Response(false, false, "Error during file retrieving!", errorResponse);
        }       
    }

and FileTransfer is:

    public class FileTransfer {

        private byte[] content;
        private String name;
..get and set

client class:

    @RequestMapping(value = "/", method = RequestMethod.GET)
public @ResponseBody Response getFile(@RequestParam(value="path", defaultValue="/home") String path){
    RestTemplate restTemplate = new RestTemplate();
    Response response = restTemplate.getForObject("http://localhost:8086/ATS/client/file/?path={path}", Response.class, path);
    if (response.isStatus() && response.isSuccess()){
        try {
            @SuppressWarnings("unchecked")
            LinkedHashMap<String,String> result= (LinkedHashMap<String,String>)response.getResult();
            //byte[] parseBase64Binary = DatatypeConverter.parseBase64Binary((String)fileTransfer.getContent());
            Files.write(Paths.get(result.get("name")), DatatypeConverter.parseBase64Binary(result.get("content"))); 
            return new Response(true, true, "Your file has been written!", null);
            } catch (IOException e) {
            return new Response(true, true, "Error writing your file!!", null);
        }
    }
    return response;
}
5
  • 1
    Can you show how you defined the rest endpoint and such? What content type is it accepting? if it's json, then byte[] would be sent as Base64 encoded string. Given the right mapper you can get this as byte[]. Commented Nov 24, 2015 at 15:12
  • yes I'm using json. I updated the above code Commented Nov 24, 2015 at 15:15
  • How does your Response class look like? It should not contain Object it should be a byte[] field. Commented Nov 24, 2015 at 15:40
  • it contains object because Response is used for all web service Commented Nov 24, 2015 at 15:59
  • I'd consider changing the response class if you don't actually have the same response all the time. "Q2lhbyBNb25kbw==" is otherwise just a string for the deserializer. If you tell it to deserialize e.g. a BinaryResponse class that has a byte[] field it would do the datatype conversion stuff for you. Response<GenericType> (not sure if that works thouhg) or sub classes Commented Nov 24, 2015 at 16:07

2 Answers 2

2

So the client should be something like this

@RequestMapping(value = "/test/", method = RequestMethod.GET)
    public Response getFileTest(@RequestParam(value="path", defaultValue="/home") String path){
        RestTemplate restTemplate = new RestTemplate();
        Response response = restTemplate.getForObject("http://localhost:8086/ATS/client/file/?path={path}", Response.class, path);
        if (response.isStatus() && response.isSuccess()){
            try {
                byte[] parseBase64Binary = DatatypeConverter.parseBase64Binary((String)response.getResult());
                Files.write(Paths.get("test.txt"),parseBase64Binary );
            } catch (IOException e) {
            }
        }
        return response;
    }
Sign up to request clarification or add additional context in comments.

6 Comments

it works, great. Is there a way to retrieve the file name and extension(otherwise I don't know the original file)? or I have tu use an object with name and file?
you have to use an object with name and file.. byte array is only the content of the file
I update with new and working code, do you think it is correct? I had to use LinkedHashMap<String,String> instead of FileTrasfer because otherwise I received exception
what was the exception
it is not possible cast LinkedHashMap in FileTrasfer, getForObject return Response object but with LinkedHashMap instead of FileTrasfer
|
0

I believe the content-type here is text/plain, therefore the content of the file is a plain text. Simply generate byte array from the response:

 Files.write(Paths.get("test.txt"),((String)response.getResult()).getBytes());

3 Comments

as I have written in the main post, if I cast to String and use getBytes I receive not "Hello world" but "Q2lhbyBNb25kbw==".
@luca which is Base64 for "Ciao Mondo" - see awsome.
might want to be explicit in specifying the Charset when it comes to encoding Strings to bytes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.