我想通过 http 发送一个大对象(比如 4G)。我们有一个自定义序列化程序,可以将对象写入 OutputStream。目前我们将对象写入磁盘并将该文件用于用于请求的输入流。像这些行:private static Response sendObject(Object bigObject) throws IOException { File tempFile = File.createTempFile("x", "y"); OutputStream out = new FileOutputStream(tempFile); CustomSerializer.serialize(bigObject, out); out.close(); WebTarget resource = service.path("data"); FormDataMultiPart multiPartEntity = new FormDataMultiPart(); InputStream inputStream = new FileInputStream(tempFile); StreamDataBodyPart streamBodyPart = new StreamDataBodyPart( "data", inputStream, "data", MediaType.APPLICATION_OCTET_STREAM_TYPE); MultiPart multiPart = multiPartEntity.bodyPart(streamBodyPart); return resource.request(MediaType.APPLICATION_JSON_TYPE) .post(Entity.entity(multiPart, multiPart.getMediaType())); }我们节省了一些内存,因为我们没有序列化到内存中的字节数组。那很好。但是我可以在不写入磁盘的情况下保存内存吗?您可以直接写入输入流而不重写 CustomSerializer 吗?您可以在读入请求时直接写入输入流吗?——这有点难以解释,但我想我在追求这样的伪代码:private static Response sendObject(Object bigObject) throws IOException { WebTarget resource = service.path("data"); FormDataMultiPart multiPartEntity = new FormDataMultiPart(); // A type of stream I don't know if exist OutputStream outIn = new OutputInputStream() { public void openInputStream() { CustomSerializer.serialize(bigObject, this); } }; StreamDataBodyPart streamBodyPart = new StreamDataBodyPart( "data", outIn.getInputStream(), "data", MediaType.APPLICATION_OCTET_STREAM_TYPE); MultiPart multiPart = multiPartEntity.bodyPart(streamBodyPart); return resource.request(MediaType.APPLICATION_JSON_TYPE) .post(Entity.entity(multiPart, multiPart.getMediaType()));}
1 回答
心有法竹
TA贡献1866条经验 获得超5个赞
您可以使用 aStreamingOutput并使用您CustomSerializer的写入提供的OutputStream
StreamingOutput entity = new StreamingOutput() {
@Override
public void write(OutputStream out)
throws IOException, WebApplicationException {
CustomSerializer.serialize(bigObject, out);
}
};
该write()方法将由 Jersey 调用,让您有机会直接写入响应实体流。
然后只需使用一个 FormDataBodyPart
BodyPart bigPart = new FormDataBodyPart(
"data", entity, MediaType.APPLICATION_OCTET_STREAM_TYPE);
MultiPart multiPart = new FormDataMultiPart().bodyPart(bigPart);
添加回答
举报
0/150
提交
取消