Android API Calls With Retrofit

From ESE205 Wiki
Revision as of 09:59, 19 April 2019 by Orrbradford (talk | contribs) (added initial stuff)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

This tutorial will guide you through the process of calling an api using an android library called Retrofit. This tutorial will be limited to the api call and will not take you through the finer points of design or string parsing. It also will not show you how to create your own api but if you did create your own you could use this library to call it.

Download Android Studio Create New Project with Blank activity. Set the targeted API level to 21. First we want to add the libraries we will be using to our android app. You will need to go to the app's build.gradle file. This can be found under the Gradle Scripts Directory. Note that there are two build.gradle files. One if for your application and one is for your project. The app build.gradle will have the android compilesdkversion near the top. Add the following lines under dependencies to add the proper libraries. You may get a prompt to sync your project after adding these. Go ahead and do so.

 implementation 'com.squareup.retrofit2:retrofit:2.5.0'
 implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
 implementation 'com.squareup.okhttp3:logging-interceptor:3.12.1'

We'll be using the internet so we also need to declare this in our app manifest. Navigate to the manifest directory and open the AndroidManifest.xml file. Above the application tag you wan to add this line

 <uses-permission android:name="android.permission.INTERNET" />

Now if your api is using cleartext traffic (any url that is Http instead of Https) then you also want to add the filling line to the application tag.