我有一个Jersey 2应用程序,其中包含消耗和生成json的资源。我的要求是为从各种响应数据(类似于Amazon Webservices请求签名)的组合生成的Authorization响应头添加签名。其中一个数据是响应主体,但我看不出有任何过滤器或拦截点可以让我访问json内容。我想这主要是因为响应输出流是用于写入而不是读取。
关于我如何阅读回应机构或其他方法的任何想法?
谢谢。
答案 0 :(得分:0)
您可以实现ContainerRequestFilter以访问内容,并在完成拦截逻辑后,将其转发给请求。 E.g。
import java.io.*;
import com.sun.jersey.api.container.ContainerException;
import com.sun.jersey.core.util.ReaderWriter;
import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerRequestFilter;
public class ExampleFilter implements ContainerRequestFilter {
@Override
public ContainerRequest filter(ContainerRequest req) {
try(InputStream in = req.getEntityInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream();) {
if (in.available() > 0) {
StringBuilder content = new StringBuilder();
ReaderWriter.writeTo(in, out);
byte[] entity = out.toByteArray();
if (entity.length > 0) {
content.append(new String(entity)).append("\n");
System.out.println(content);
}
req.setEntityInputStream(new ByteArrayInputStream(entity));
}
} catch (IOException ex) {
//handle exception
}
return req;
}
}
答案 1 :(得分:0)
我的理解是,当您的应用程序响应请求时,您希望通过为其值添加签名来修改Authorization
标头。
如果是这种情况,您希望实现ContainerResponseFilter
:
public class MyContainerResponseFilter implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext containerRequestContext, ContainerResponseContext containerResponseContext) throws IOException {
// You can get the body of the response from the ContainerResponseContext
Object entity = containerResponseContext.getEntity();
// You'll need to know what kind of Object the entity is in order to do something useful though
// You can get some data using these functions
Class<?> entityClass = containerResponseContext.getEntityClass();
Type entityType = containerResponseContext.getEntityType();
// And/or by looking at the ContainerRequestContext and knowing what the response entity will be
String method = containerRequestContext.getMethod();
UriInfo uriInfo = containerRequestContext.getUriInfo();
// Then you can modify your Authorization header in some way
String authorizationHeaderValue = containerResponseContext.getHeaderString(HttpHeaders.AUTHORIZATION);
authorizationHeaderValue = authorizationHeaderValue + " a signature you calculated";
containerResponseContext.getHeaders().putSingle(HttpHeaders.AUTHORIZATION, authorizationHeaderValue);
}
}
请注意,即使Jersey无法找到请求路径的匹配资源,也会为您的应用程序的所有请求调用filter
函数,因此您可能需要进行一些额外的检查。