在Jersey JAX-RS服务器中返回大对象时如何设置Content-Length [英] How do I set Content-Length when returning large objects in Jersey JAX-RS server
问题描述
有时我想返回一个大的(几个MB)二进制对象作为JAX-RS资源方法的响应.我知道对象的大小,并且我希望在响应中设置Content-Length标头,并且我不希望使用分块传输编码.
I sometimes want to return a large (several MB) binary object as a response from a JAX-RS resource method. I know the size of the object, and I want the Content-Length header to be set on the response, and I don't want chunked transfer encoding to be used.
在Jersey 1.x中,我使用自定义的MessageBodyWriter解决了这个问题:
In Jersey 1.x, I solved this with a custom MessageBodyWriter:
public class Blob {
public InputStream stream;
public long length;
}
@Provider
public class BlobWriter extends MessageBodyWriter<Blob> {
public boolean isWriteable(Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return Blob.class.isAssignableFrom(type);
}
public long getSize(T t, Class<?> type, Type genericType, Annotation[] annotations,
MediaType mediaType) {
return t.length;
}
public void writeTo(T t, Class<?> type, Type genericType, Annotation[] annotations,
MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders,
OutputStream entityStream)
throws java.io.IOException {
org.glassfish.jersey.message.internal.ReaderWriter.writeTo(t.stream, entityStream);
}
}
但是当我升级到Jersey 2.x时,此操作停止了,因为JAX-RS/Jersey 2不再关心MessageBodyWriter.getSize()了.我该如何使用Jersey 2做到这一点?
But this stopped working when I upgraded to Jersey 2.x, since JAX-RS/Jersey 2 does not care about MessageBodyWriter.getSize() anymore. How can I accomplish this with Jersey 2?
推荐答案
似乎可以使用提供的httpHeaders从MessageBodyWriter.writeTo()设置Content-Length标头:
It seems to be possible to set the Content-Length header from MessageBodyWriter.writeTo() using the supplied httpHeaders:
public void writeTo(T t, Class<?> type, Type genericType, Annotation[] annotations,
MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders,
OutputStream entityStream)
throws java.io.IOException {
httpHeaders.addFirst(HttpHeaders.CONTENT_LENGTH, t.length.toString);
org.glassfish.jersey.message.internal.ReaderWriter.writeTo(t.stream, entityStream);
}
这篇关于在Jersey JAX-RS服务器中返回大对象时如何设置Content-Length的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!