Android How to add a custom header in grpc client? Android How to add a custom header in grpc client? android android

Android How to add a custom header in grpc client?


The edited version in the question works too.In GRPC there are many ways to add headers (called meta data) . We can add meta data like in my question above using interceptor or we can add meta data for the client stub or you can add it before making request in the client stub channel .

// create a custom headerMetadata header=new Metadata();Metadata.Key<String> key =    Metadata.Key.of("Grps-Matches-Key", Metadata.ASCII_STRING_MARSHALLER);header.put(key, "match.items");// create client stubServiceGrpc.ServiceBlockingStub stub = ServiceGrpc    .newBlockingStub(channel);

Add the header before making any request as shown here using MetadataUtils

stub = MetadataUtils.attachHeaders(stub, header);


For Kotlin Lover

    private fun getHeaderMetaData(): io.grpc.Metadata {        val header: io.grpc.Metadata = io.grpc.Metadata()        val channel: io.grpc.Metadata.Key<String> = io.grpc.Metadata.Key.of("channel", io.grpc.Metadata.ASCII_STRING_MARSHALLER)        val api_key: io.grpc.Metadata.Key<String> = io.grpc.Metadata.Key.of("api-key", io.grpc.Metadata.ASCII_STRING_MARSHALLER)        val lang: io.grpc.Metadata.Key<String> = io.grpc.Metadata.Key.of("lang", io.grpc.Metadata.ASCII_STRING_MARSHALLER)        header.put(channel, "AND")        header.put(api_key, "dummykey")        header.put(lang, "en")        return header    }

and call this header

   var stub = FlightSearchGrpc.newBlockingStub(channel)   stub = io.grpc.stub.MetadataUtils.attachHeaders(stub, getHeaderMetaData())