java - 为什么我的二进制数据从网络服务器获取后会变大?

标签 java python django file byte

我需要通过 Python/Django 实现的 Web 服务提供二进制文件。问题是,当我使用 vbindiff 将原始文件与传输的文件进行比较时,我看到传输的文件上有尾随字节,遗憾的是它变得毫无用处。

客户端使用 Java 访问保存的二进制文件:

HttpURLConnection userdataConnection = null;
    URL userdataUrl = null;
    try {
        userdataUrl = new URL("http://localhost:8000/app/vuforia/10");

        userdataConnection = (HttpURLConnection) userdataUrl.openConnection();
        userdataConnection.setRequestMethod("GET");
        userdataConnection.setRequestProperty("Content-Type", "application/octet-stream");
        userdataConnection.connect();

        InputStream userdataStream = new BufferedInputStream(userdataConnection.getInputStream());
        try (ByteArrayOutputStream fileStream = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[4094];
            while (userdataStream.read(buffer) != -1) {
                fileStream.write(buffer);
            }
            byte[] fileBytes = fileStream.toByteArray();
            try (FileOutputStream fos = new FileOutputStream("./test.dat")) {
                fos.write(fileBytes);
            }
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

我认为 HttpURLConnection.getInputStream 只读取响应的正文,或者不读取?

此代码在后端提供数据

在views.py中:

if request.method == "GET":
    all_data = VuforiaDatabase.objects.all()
    data = all_data.get(id=version)
    return FileResponse(data.get_dat_bytes())

在 models.py 中:

def get_dat_bytes(self):
    return self.dat_upload.open()

如何以 1:1 的方式传输二进制数据?

最佳答案

您忽略了InputStream.read的返回值。

来自documentation :

Returns:

the total number of bytes read into the buffer, or -1 if there is no more data because the end of the stream has been reached.

您的代码假设每次调用 userdataStream.read(buffer) 时都会填充缓冲区,而不是检查实际读入 buffer 的字节数。

您根本不需要从输入流中读取。只需使用 Files.copy :

Path file = Paths.get("./test.dat");

try (InputStream userdataStream = new BufferedInputStream(userdataConnection.getInputStream())) {
    Files.copy(userdataStream, file, StandardCopyOption.REPLACE_EXISTING);
}

关于java - 为什么我的二进制数据从网络服务器获取后会变大?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52337479/

相关文章:

java - Java 内存模型中的部分构造对象

python - 查看文件是否存在并打印

python - 如何从模板调用模型函数?

java - Q : Converting Avro to Parquet in Memory

java - 如果配置服务器关闭,Spring Cloud 配置客户端会加载本地属性

python - 在 Python 中通过 ssh 实现 hdf5

python - Python 中是否有一种简单的方法来创建一个可以在一个线程中写入并在不同线程中读取的文件?

python - 阻止 Django 缩小我的 less 文件

Django 忽略了我的 TestCase 装置

java - 如何序列化 Jackson Joda 日期格式?