Top Retrofit Library Network Tips and Tricks for api calls

shivam kewat
2 min readAug 5, 2021

--

Hii there folks! Welcome

I hope you very good in the android development industry! WELL if you do network calls, there is no doubt that you have not came across one of the best library for rest calls! Retrofit,

But as you go through this library you may came across some difficult when requesting post request or multiform request , file upload request and any other! Without further a due let me share you some helpful tips doing most used post request

Example 1: Let say we want to post in the api with JSONbody and headers, how are api interface gonna look like , See our content data below

{

“address1”: “998 Toa Payoh N1”,

“address2”: “998 Toa Payoh N2”,

“address3”: “998 Toa Payoh N3”,

“address4”: “998 Toa Payoh N4”,

}

How to use these above method! Our first parameter annotated with @Header so it require header value mostly of type String, it mostly used for sending JSONWeb token for authorization purposes , and second one Content-Type for setting the post content type

There and important one is sending the JSONData , we have used here @Body annotation with type HashMap<String, Any>

Lets see the actual usage of the method

Example 2: Let say we have use case to send post request with some header and form-data type for the content

Sample screenshot for sending data in postman

You can use the same implementation which we have used in Example 1 , Only difference in above method that we are adding another annotation @FormUrlEncoded for stating that it is form-data request and @FieldMap annotation for the sending the content instead of @Body

If you have only one or two string to send, then you can use @Field annotation instead of @FieldMap, Like below

@POST("api/feedback/SaveFeedbackResponse")
@FormUrlEncoded
suspend fun postFeedbackWithField(@Header("Authorization") token:String,@Field("jptranssn") name:String, @Field("dob") dob:String):Response<RegisterResponse>

Example 3: Let see some example of how to send GET request with query type like below

api/feedback/Details?fqsn=14&jptransactionsn=9

As you can see in the above method for sending query parameters
?fqsn=14&jptransactionsn=9

We have used @Query annotation with parameter string name which is (“fqsn”) and another one (“jptransactionsn”)

That’s it for now! Well there more of you, I will be updating this post as i go through various use cases, So Stay tuned

Thanks For Reading :)

--

--

shivam kewat
shivam kewat

Written by shivam kewat

Hello there Devs! I like building apps for the worlds ...

No responses yet