我需要通过 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/