Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Optional parameter in retrofit method

I have 2 methods:

@POST("/example")
fun getSomething(@Body string: String)

@POST("/example")
fun getSomethingWithHeader(@Body string: String, @Header header: String)

Sometimes I have to post with header sometimes without, it works but in my opinion it could be one method especially with kotlin default args.

But something like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@POST("/example")
fun getSomethingWithHeader(@Body string: String, @Header header: String = "")

will probably send also header but empty.

Is it possible to merge these 2 method into 1 ?

>Solution :

Define the header as nullable like this:

@POST("/example")
fun getSomethingWithHeader(
    @Body string: String, 
    @Header("YourHeader") header: String? = null
)

From https://square.github.io/retrofit/:

If the value is null, the header will be omitted. Otherwise, toString
will be called on the value, and the result used.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading