Skip to main content

How to upload a file using OKHTTP in Kotlin Android

How to upload a file using OKHTTP in Kotlin Android.

Here is a detailed step-by-step tutorial on how to upload a file using OKHTTP in Kotlin Android:

Step 1: Add dependencies

To begin, you need to add the OKHTTP library to your Android project. Open your app-level build.gradle file and add the following dependency:

implementation 'com.squareup.okhttp3:okhttp:4.9.1'

Step 2: Create an HTTP client

Next, you need to create an instance of the OkHttpClient class. This class is responsible for making HTTP requests. You can configure various settings such as timeouts, interceptors, etc. In this example, we will use the default settings:

val client = OkHttpClient()

Step 3: Create a request body

Before uploading a file, you need to create a RequestBody object that represents the file you want to upload. You can use the MultipartBody.Builder class to build the request body. Here's an example:

val file = File("/path/to/file.jpg")

val requestBody = MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", file.name, RequestBody.create(MediaType.parse("image/jpeg"), file))
.build()

In the example above, we create a File object that represents the file we want to upload. Then, we use the MultipartBody.Builder to build the request body. We set the type to MultipartBody.FORM and add a form data part with the file name and its content type.

Step 4: Create a request

Next, we need to create an instance of the Request class. This class represents an HTTP request. We can set various properties such as the URL, method, headers, etc. Here's an example:

val request = Request.Builder()
.url("https://example.com/upload")
.post(requestBody)
.build()

In the example above, we create a Request.Builder and set the URL to the endpoint where we want to upload the file. We use the post() method to set the HTTP method to POST and pass the request body we created in the previous step.

Step 5: Execute the request

Finally, we need to execute the request using the HTTP client we created earlier. We can do this by calling the newCall() method on the client and passing the request as a parameter. Here's an example:

client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
// Handle the failure
}

override fun onResponse(call: Call, response: Response) {
// Handle the response
}
})

In the example above, we call the enqueue() method instead of execute() to execute the request asynchronously. We pass a callback object that will be called when the request completes. You can handle the failure and success cases in the respective methods of the callback.

That's it! You have successfully uploaded a file using OKHTTP in Kotlin Android. Remember to handle any exceptions that may occur during the process and add the necessary permissions to your Android manifest file if required.