2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Android で gRPC通信 をする時に MetaData を使いたい!

Last updated at Posted at 2019-01-08

gRPC on Androidの正しい新しい記事が少ない為書きました.

AndroidでgRPCを使っていて,MetaDataを使いたくなったら以下のように書くといいです.

keyがauthorizationsession $sessionIdをMetadataに入れる例を示します.

UserServiceClient.kt

class UserServiceClient{

    private val channel: ManagedChannel = ManagedChannelBuilder
            .forAddress(BuildConfig.SERVER_URL, BuildConfig.PORT.toInt())
            .useTransportSecurity()
            .build()

    private var userStub: UserServiceGrpc.UserServiceBlockingStub = UserServiceGrpc.newBlockingStub(channel)

    suspend fun user(sessionId: String) = coroutineScope {

        Metadata().apply {
            put(Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER), "session $sessionId")
        }.let {
            //  この,stubに代入してあげるのを忘れると積むので気をつけること!!
            userStub = MetadataUtils.attachHeaders(userStub, it)
        }

        val createRequest = Users.GetCurrentUserRequest.newBuilder()
                .build()

        userStub.getCurrentUser(createRequest)
    }
}

協力: @gedorinku ありがとうございます!!

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?