发送字节数组并通过REST Web服务接收String

时间:2015-11-24 15:07:35

标签: java spring file rest bytearray

在我的Spring Rest Web服务中,我发送一个文件(甚至是大尺寸)作为字节数组,但是当我收到信息时,对象是一个String,所以当我从Object转换为byte []时,我收到以下错误:

  

java.lang.ClassCastException:java.lang.String无法强制转换为[B

原始文件通过

转换

Files.readAllBytes(Paths.get(path))

并且此byte[]填充在一个对象类型为result的对象中。 当客户端检索此对象并获得result类并转换为byte[]时,会出现上述异常,这是客户端代码

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

如果我使用强制转换为字符串然后使用字节,则文件的内容与原始文件不同。我不关心文件类型,文件内容,我只需要从服务器复制到客户端目录 我该怎么办?谢谢

服务器类:

@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);
        }       
    }

和FileTransfer是:

    public class FileTransfer {

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

客户端类:

    @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;
}

2 个答案:

答案 0 :(得分:2)

所以客户端应该是这样的

PIVOT (
    COUNT(DUMMY) POSTFIX
    FOR DUMMY IN ('X' ALIAS)
)

答案 1 :(得分:0)

我相信这里的内容类型是text/plain,因此文件的内容是纯文本。只需从响应中生成字节数组:

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