I am trying to set the Content-MD5 header on a request created with the Jersey Client API. I have created ClientFilter which implements another adapter (similar to how the GZipFilter works). Like this:
public class ContentMD5Filter extends ClientFilter {
private static final class ContentMD5Adapter extends AbstractClientRequestAdapter {
ContentMD5Adapter(final ClientRequestAdapter cra) {
super(cra);
}
@Override
public OutputStream adapt(final ClientRequest request, final OutputStream out) throws IOException {
try {
MessageDigest instance = MessageDigest.getInstance("MD5");
request.getHeaders().add("Content-MD5", instance);
return new DigestOutputStream(out, instance);
} catch (NoSuchAlgorithmException e) {
throw new WebApplicationException();
}
}
}
@Override
public ClientResponse handle(final ClientRequest cr) throws ClientHandlerException {
cr.setAdapter(new ContentMD5Adapter(cr.getAdapter()));
return getNext().handle(cr);
}
}
This doesn’t work, as the digest are read to early (ie. before the whole content is written.
Any ideas on how to do this? As well as setting the header, I need to access it in another filter afterwards (to implement a security mechanism)
I found the solution. It’s a quite complex way to do it, since I have to temporarily store the outputstream, but I guess you can figure it out if you need this yourself 🙂
The code for the filter:
To use this filter: