這是另一個例子。我通過ByteArrayOutputStream
創建QRCode作爲PNG。資源返回一個Response
對象,流的數據是實體。
爲了說明響應代碼處理,我添加了處理緩存標頭(If-modified-since
,If-none-matches
等)。
@Path("{externalId}.png")
@GET
@Produces({"image/png"})
public Response getAsImage(@PathParam("externalId") String externalId,
@Context Request request) throws WebApplicationException {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// do something with externalId, maybe retrieve an object from the
// db, then calculate data, size, expirationTimestamp, etc
try {
// create a QRCode as PNG from data
BitMatrix bitMatrix = new QRCodeWriter().encode(
data,
BarcodeFormat.QR_CODE,
size,
size
);
MatrixToImageWriter.writeToStream(bitMatrix, "png", stream);
} catch (Exception e) {
// ExceptionMapper will return HTTP 500
throw new WebApplicationException("Something went wrong …")
}
CacheControl cc = new CacheControl();
cc.setNoTransform(true);
cc.setMustRevalidate(false);
cc.setNoCache(false);
cc.setMaxAge(3600);
EntityTag etag = new EntityTag(HelperBean.md5(data));
Response.ResponseBuilder responseBuilder = request.evaluatePreconditions(
updateTimestamp,
etag
);
if (responseBuilder != null) {
// Preconditions are not met, returning HTTP 304 'not-modified'
return responseBuilder
.cacheControl(cc)
.build();
}
Response response = Response
.ok()
.cacheControl(cc)
.tag(etag)
.lastModified(updateTimestamp)
.expires(expirationTimestamp)
.type("image/png")
.entity(stream.toByteArray())
.build();
return response;
}
請不要在情況stream.toByteArray()
打我是一個沒有任何記憶明智:)它適合我的< 1KB PNG文件...
+1 - 非常好的例子 – 2011-03-29 08:20:22
也可以將StreamingOutput作爲實體返回給'Response'對象。這樣你可以很容易地控制mediatype,HTTP響應代碼等。讓我知道你是否希望我發佈代碼。 – Hank 2011-06-28 13:29:33
@Hank,是的,請張貼代碼 – MyTitle 2012-09-20 13:37:31