What is Retrofit Library and How to send PUT and POST method in the retrofit?
Retrofit Library is a REST Client for Android and Java by Square. It makes relatively easy to send and retrieve JSON (or other structured data) via rest Webservice. In Retrofit, we can configure which converter is used for the data serialization.
When we want to send JSON request data then we use @body annotation in our Request call and pass our request model with @body in the request, and set the content type application/json in the header.
We can also use @Field
Annotation, so, we must put @FormUrlEncoded
in our API call.
- here is our Interface Request Function that is the structure of our request. We use @Body tag and pass AddToCartRequest model class in the request.
1234567891011@POST(MOBIKUL_ADD_TO_CART_DATA)Call<AddToCartResponseModel> addtoCartPost(@Header("Authorization") String authkey, @Header("Content-Type") String contentType, @Path("customerId") String customerId, @Query("width") int width, @Query("lang_code") String langCode, @Query("currency_code") String currencyCode, @Body AddToCartRequest request);
- here is function of calling add to cart API via Retrofit Client.
123456789101112public static void addToCartPost(Context mContext, Callback<AddToCartResponseModel> callback, AddToCartRequest request){Call<AddToCartResponseModel> call = RetrofitClient.getClient(mContext).create(ApiInterface.class).addtoCartPost(Helper.getAuthToken(),"application/json", AppSharedPref.getCustomerId(mContext), Utils.getScreenWidth(), AppSharedPref.getLanguageCode(mContext), AppSharedPref.getCurrencyCode(mContext), request);call.enqueue(callback);}
- now our AddToCartRequest model class.
12345678910111213public class AddToCartRequest {@SerializedName("product_data")@Exposeprivate ProductData productData;public ProductData getProductData() {return productData;}public void setProductData(ProductData productData) {this.productData = productData;}}
Retrofit library converts AddToCartRequest Model class in proper JSON format.
1{"product_data":{"amount":"1","extra":{},"product_id":"54","product_options":{}}}