在API中发送视频文件

时间:2016-10-05 12:13:20

标签: android api

我需要在Json中制作API来发送视频。我不想发送视频路径。以JSON发送视频的最佳方式是什么,将由Android和iPhone家伙使用。如果我使用base64或byte [],那么我将收到内存异常错误。

1 个答案:

答案 0 :(得分:0)

File file = new File("video.mp4");

FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
try {
    for (int readNum; (readNum = fis.read(buf)) != -1;) {
         bos.write(buf, 0, readNum); //no doubt here is 0
         System.out.println("read " + readNum + " bytes,");
     }
 } catch (IOException ex) {
        Logger.getLogger(genJpeg.class.getName()).log(Level.SEVERE, null, ex);
 }
 byte[] bytes = bos.toByteArray();

这是在字节数组中逐字节添加视频的方法。然后,您可以通过以下方式将字节数组作为JSONOBject发送...

byte[] data; //array holding the video
String base64Encoded = DatatypeConverter.printBase64Binary(data); //You have encoded the array into String

now send that to server. (I am guessing you know how to)..

这就是你将JSON再次解码为byteArray的方法。

byte[] base64Decoded = DatatypeConverter.parseBase64Binary(base64Encoded);

在json中发送二进制文件的典型方法是对其进行base64编码。 Java为Base64编码和解码byte []提供了不同的方法。其中之一是DatatypeConverter。

我希望它有所帮助。 干杯!

编辑: 你得到OutOfMemoryException,因为HeapMemory的大小是2Mb而你的视频是2Mb,所以当插入String时,它会耗尽内存。即使您将其放入Object实例中,您也必须重新初始化堆或其他方式。我明天会写一个答案。 (写下这半睡半醒,可能是另一种方式_