Java 通过 REST web 服务发送字节数组并接收字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33897107/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 15:08:09  来源:igfitidea点击:

Send byte array and receive String through REST web service

javaspringfilerestbytearray

提问by luca

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:

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

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

java.lang.ClassCastException: java.lang.String 不能转换为 [B

The originl file is converted through

原始文件通过

Files.readAllBytes(Paths.get(path))

Files.readAllBytes(Paths.get(path))

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

byte[]在一个对象中填充了一个对象result类型的字段。当客户端检索此对象并通过强制转换获取resultbyte[]时出现上述异常,这是客户端代码

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

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:

和 FileTransfer 是:

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

采纳答案by awsome

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

回答by mtyurt

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:

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

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