首先增加一个 ClientInterceptor 拦截器
public class HeaderClientInterceptor implements ClientInterceptor {
private Map<String, String> requestHeaders;
public HeaderClientInterceptor(final Map<String, String> requestHeaders) {
this.requestHeaders = requestHeaders;
}
@Override
public <Q, P> ClientCall<Q, P> interceptCall(final MethodDescriptor<Q, P> methodDescriptor,
final CallOptions callOptions, final Channel channel) {
return new ForwardingClientCall.SimpleForwardingClientCall<Q, P>(
channel.newCall(methodDescriptor, callOptions)) {
@Override
public void start(final Listener<P> responseListener, final Metadata headers) {
if (requestHeaders != null && !requestHeaders.isEmpty()) {
requestHeaders.entrySet().forEach(item -> {
Metadata.Key<String> metadataKey =
Metadata.Key.of(item.getKey(), Metadata.ASCII_STRING_MARSHALLER);
headers.put(metadataKey, item.getValue());
});
}
super.start(responseListener, headers);
}
};
}
}
然后将拦截器与channel结合使用即可:
Channel newChannel = ClientInterceptors.intercept(channel, new HeaderClientInterceptor(headers));