Connecting Android Studio and SpringBoot
Connecting Android Studio and SpringBoot
2. Get the Libraries needed for http communication from Maven Repository.
Retrofit – is type-safe REST client for Android and Java which aims to make it easier to consume RESTful
web services. Retrofit 2 by default leverages OkHttp as the networking layer and is built on top of it. (It is
easier to construct the http request using retrofit compared to OkHttp. Retrofit is an improved version
of OkHttp) Retrofit automatically serialises the JSON response using a POJO(Plain Old Java Object) which
must be defined in advanced for the JSON Structure. To serialise JSON we need a converter to convert it
into Gson first.
Converter Gson – the data to be used for reading and posting are in json format. We need an adapter or
converter that will easily convert the request and response to and into json.
.
Note: There will be errors after adding the retrofit and gson dependencies. Edit them as follows:
// https://mvnrepository.com/artifact/com.squareup.retrofit2/retrofit
implementation("com.squareup.retrofit2:retrofit:2.9.0")
// https://mvnrepository.com/artifact/com.squareup.retrofit2/converter-gson
implementation("com.squareup.retrofit2:converter-gson:2.9.0")
You should be able to build the project without errors after adding these 2 libraries.
4. Create the object model. (Just copy the “User” object model from Springboot project then paste
in the “model” package in android studio. Remove annotations). Result is as follows:
5. Add a package named retrofit then create a class named RetrofitService. We will initialize
retrofit to enable communication between the android app and the SpringBoot server.
6. Write the following codes
Specify the location of the Springboot server. You can check the address as follows:
For the server port addess, check from IntelliJ as follows
7. Specify the API structure. To do this, create a UserAPI interface and write the codes shown
below.
Check the URI/paths against the ones specified in the SpringBoot API
10. We need to give permission to our app for the network access so we need to add 2 permissions
in AndroidManifest.xml. Write the codes shown below.
10 . It is also possible to get the following error in accessing the port which is there to guard against http
requests.
b. Run the Springboot UserAPI application. Extract the attached UserApi.zip provided here and
run it in IntelliJ using this command mvn spring-boot:run