Network Requests with Retrofit in Android

Jun 5 2024 · Kotlin 1.9.22, Android 14, Android Studio Hedgehog | 2023.1.1

Lesson 03: Make a Request With Retrofit

Demo

Episode complete

Play next episode

Next

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Preparing the Service

To start, open MovieDiaryApiService.kt and replace the code inside with the following:

@POST("user/register")
fun registerUser(@Body body: RequestBody): Call<ResponseBody>

@POST("user/login")
fun loginUser(@Body body: RequestBody): Call<ResponseBody>

@GET("user")
fun getProfile(): Call<ResponseBody>

@GET("sampleMovies")
fun getMovies(): Call<ResponseBody>

@POST("movies")
fun postReview(@Body body: RequestBody): Call<ResponseBody>

Replacing HttpUrlConnection with Retrofit

With the service methods ready, navigate to MovieDiaryApi.kt and delete the old registerUser method. You’ll implement it again to work with Retrofit. To start, add the following code:

fun registerUser(
  username: String,
  email: String,
  password: String,
  onResponse: (String?, Throwable?) -> Unit,
) {}
val jsonBody = JSONObject().apply {
  put("username", username)
  put("email", email)
  put("password", password)
}.toString()
val body = RequestBody.create(MediaType.parse("application/json"), jsonBody)
apiService.registerUser(body).enqueue(object : Callback<ResponseBody> {
  override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {

  }

  override fun onFailure(call: Call<ResponseBody>, error: Throwable) {

  }
})
onResponse(null, error)
val message = response.body()?.string()
if (message == null) {
  val error = response.errorBody()?.string()
  onResponse(null, Throwable(error))
  return
} else {
  onResponse(message, null)
}

Implementing User Login

Implement loginUser in the same way as registerUser. Remove the suspend modifier from the method and update loginUser with the following:

fun loginUser(username: String, password: String, onResponse: (String?, Throwable?) -> Unit) {
  val jsonBody = JSONObject().apply {
    put("username", username)
    put("password", password)
  }.toString()

  val body = RequestBody.create(MediaType.parse("application/json"), jsonBody)

  apiService.loginUser(body).enqueue(object : Callback<ResponseBody> {
    override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
      val message = response.body()?.string()
      if (message == null) {
        val error = response.errorBody()?.string()
        onResponse(null, Throwable(error))
        return
      } else {
        
      }
    }

    override fun onFailure(call: Call<ResponseBody>, error: Throwable) {
      onResponse(null, error)
    }
  })
}
JSONObject(message).run {
  val token = getString("token")
  onResponse(token, null)
}

Fetching the Movies

Navigate back to MovieDiaryApi.kt and scroll down to getMovies. Replace the comment with the following code:

apiService.getMovies().enqueue(object : Callback<ResponseBody> {
  override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {

  }

  override fun onFailure(call: Call<ResponseBody>, error: Throwable) {
    onResponse(null, error)
  }
})
if (response.isSuccessful) {
  val movieReviews = mutableListOf<MovieReview>()
  JSONArray(response.body()?.string()).also { array ->
    for (i in 0 until array.length()) {
      array.getJSONObject(i).run {
        MovieReview(
          title = getString("title"),
          description = getString("description"),
          comment = getString("comment")
        ).also { movieReviews.add(it) }
      }
    }
  }
  onResponse(movieReviews, null)
}
else {
  onResponse(null, Throwable(response.errorBody()?.string()))
}
See forum comments
Cinema mode Download course materials from Github
Previous: Instruction Next: Conclusion