![]() |
VOOZH | about |
REST APIs provide us a functionality with the help of which we can add data to our database using REST API. For posting this data to our database we have to use the Post method of REST API to post our data. We can post data to our API in different formats. In this article, we will take a look at How to Post raw whole JSON in the body of a Retrofit Request. A sample video is given below to get an idea about what we are going to do in this article.
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.
Note: This Android article covered in both Java and Kotlin languages.
Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section.
// below dependency for using the retrofit
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'After adding this dependency sync your project and now move towards the AndroidManifest.xml part.
Navigate to the app > AndroidManifest.xml and add the below code to it.
Also, set the android:usesCleartextTraffic to true to allow posting to clear HTTP servers.
<application
...
android:usesCleartextTraffic="true"
...
</application>Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
activity_main.xml:
Navigate to the app > java > your app’s package name > Right-click on it > New > Kotlin class and name it as DataModal and add the below code to it. Comments are added inside the code to understand the code in more detail.
Navigate to the app > java > your app’s package name > Right-click on it > New > Java class select it as Interface and name the file as RetrofitAPI and add the below code to it. Comments are added inside the code to understand the code in more detail.
Navigate to app > java > your app's package name > MainActivity file and add the below code to it. Comments are added in the code to get to know in detail.
Now run your app and see the output of the app.
Output: