在我的Spring Rest Web服务中我发送一个文件(甚至是大尺寸)作为字节数组,但是当我收到信息时,该对象是一个String,所以当我从目的是字节[]我收到以下错误:发送字节数组并通过REST Web服务接收字符串
java.lang.ClassCastException: java.lang.String cannot be cast to [B
的originl文件通过
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);
}
}
与文件传输是:
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;
}
你能告诉你如何定义其余端点等?它接受哪种内容类型?如果它是json,那么'byte []'将作为Base64编码的字符串发送。给定正确的映射器,你可以把它作为'byte []'。 – zapl
是的,我正在使用json。我更新了上面的代码 – luca
你的'Response'类是怎么样的?它不应该包含Object,它应该是一个byte []字段。 – zapl