Contacting a Web Service
The URL that we collected in the previous tutorial is a Web service URL from which we can get to-do items… at least, in theory. In reality, it is a static JSON file pretending to be a Web service. And, since it is a static JSON file, we cannot implement a full synchronization routine, where we blend what is on the server and on the client into a unified depiction of what the state is of all of the to-do items.
However, we can implement a basic import operation. We can let the user request to import items from the server, and those that do not already exist can be added to our database and UI. So, in this tutorial, we will work on adding that capability to the app. Along the way, we will look at libraries for making HTTPS requests and for parsing JSON.
This is a continuation of the work we did in the previous tutorial. The book’s GitLab repository contains the results of the previous tutorial as well as the results of completing the work in this tutorial.
Step #1: Adding Some Dependencies
Android has an HTTPS client API built in, but it is the ancient HttpsURLConnection
, and its API leaves a lot to be desired. Similarly, Android has a couple of JSON parsers built in, but neither map JSON directly to your own objects — instead, they are classic manual parsers. None of these are especially popular.
Instead, we will use two more popular options:
- OkHttp is the most popular HTTPS client library, by far
- Moshi is a moderately popular JSON parser, from the same firm that created OkHttp
So, we need to add those to our list of dependencies. Add these three lines to the dependencies
closure in app/build.gradle
:
implementation "com.squareup.okhttp3:okhttp:4.9.1"
implementation "com.squareup.moshi:moshi:$moshi_version"
kapt "com.squareup.moshi:moshi-kotlin-codegen:$moshi_version"
Moshi requires some special stuff to work with Kotlin. Specifically, we need a Kotlin annotation processor, one that will be able to code-generate some Moshi support classes for us. That is why the third line has kapt
instead of implementation
— we are pulling in a compile-time annotation processor, not adding a runtime dependency directly.
This will give you an error, as moshi_version
is not yet defined. As before, we are using a constant to define the version, so we can have multiple dependencies with synchronized versions. Add a definition of moshi_version
to the ext
closure in the top-level build.gradle
file:
moshi_version = "1.12.0"
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.