Reading string and JSON over network
Networking is an essential component of apps. Most of the apps we use are connected to the internet and involve reading/writing data over the internet. In this recipe, we will learn how to perform network requests in Kotlin. Although you can also use a third-party library such as Retrofit, Volley and such, understanding how it's done in Kotlin is worthwhile. So let's get started!
Getting ready
We will be working with Android code, so I'll be using Android Studio. It's also required to include the anko-commons library as we will be using its methods in our code.
How to do it…
Let's follow these steps to understand how to make a network request in Kotlin:
- Making a network request in Kotlin is straightforward with simple syntax. Here's how you would read data over the internet in Kotlin:
val response = URL("<api_request>").readText()
- That's it! Remember that this is equivalent to Java code when making a network request:
// 1. Declare a URL Connection URL url...