在我的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