1.[Android (Java)]
1.1只设置客户端请求时附带的header
见类 io.grpc.stub.MetadataUtils,其中有个方法:
/** * Attaches a set of request headers to a stub. * * @param stub to bind the headers to. * @param extraHeaders the headers to be passed by each call on the returned stub. * @return an implementation of the stub with {@code extraHeaders} bound to each call. */ @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1789") public static <T extends AbstractStub<T>> T attachHeaders( T stub, final Metadata extraHeaders) { return stub.withInterceptors(newAttachHeadersInterceptor(extraHeaders)); }
稍微自己封装一下的效果,如下:
private static <T extends AbstractStub<T>> T attachHeaders(T stub, final Map<String, String> headerMap) { Metadata extraHeaders = new Metadata(); if (headerMap != null) { for (String key : headerMap.keySet()) { Metadata.Key<String> customHeadKey = Metadata.Key.of(key, Metadata.ASCII_STRING_MARSHALLER); extraHeaders.put(customHeadKey, headerMap.get(key)); } } return MetadataUtils.attachHeaders(stub, extraHeaders); }