Upload files to Google Drive with Kotlin

Lots of projects nowadays are using Google API. In this post, we will take a look at how to upload files to your Google Drive with Kotlin.

There are several available HTTP clients on JVM, however, most of them have a developer’s experience targeted on Java.

In our examples, we’re going to use kohttp, an idiomatic Kotlin DSL HTTP client.

At first, you need to add kohttp to your project dependencies

implementation(group = "io.github.rybalkinsd", name = "kohttp", version = "0.10.0")

Gradle Groovy DSL and Maven are also supported.

According to Drive API v3 a simple HTTP upload request should look like

POST https://www.googleapis.com/upload/drive/v3/files?uploadType=media 
HTTP/1.1
Content-Type: [FILE_CONTENT_TYPE]
Content-Length: [NUMBER_OF_BYTES_IN_FILE]
Authorization: Bearer [YOUR_AUTH_TOKEN]

[FILE_DATA]

Let’s have a look at how to create such a request with kohttp. As described in request spec, we need a POST request.

The only issue now is to get valid token for your request. Fortunately, here is a great article explaining the process it step by step.

httpPost is a DSL function fully featured with code completion inside your IDE. It allows adding headers, parameters, and cookies, so it will be pretty easy to add metadata to your upload request.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store