This tutorial will cover how to upload a file with OkHttp, an HTTP & HTTP/2 client for Android and Java applications, powered by Square.

1. Preparation

1.1. REST API for file uploading

Let’s assume that we have a RESTful web service which provides an API for file uploading as below:

Parameters:

Key Required Description
file required A binary file
name optional The name of the file

1.2. The client side source code

The demo source code can be found on the Github or you can download it here: Java-Examples.zip

We will use the OkHttp 3.4.1 to upload files to the REST API, and the dependency we need is:

2. Upload a File with OkHttp

In this section, we will illustrate how to make a multipart upload request using OkHttp client library.A multipart upload request allows us to send metadata along with the data to upload.

Let’s see an example code how to upload image to the above REST API:

There are a few of notices from the source code:

  • Firstly we create an instance of the MultipartBody, an RFC 2387-compliant request body, as the body of the request we will issue to the REST API.
  • Then we use the addFormDataPart method to add a form data part. The parameters for the method includes the part name, the file name and the binary file.
  • Finally, we create the request with the REST URI, the body we have just created and invoke the request.

3. Server side source code

This section describes an example of server side source code implemented for the REST API. The source code is implemented using Spring Boot and can be found on my Github project.

The upload method has only one parameter: file and the type is MulipartFile.

4. Conclusion

The tutorial has just presented how to upload a file with OkHttp. We have just performed a multipart upload to the REST API. And we also have seen an example how the server side is implemented. Note that beside the multipart upload, we can use another way to upload a file to a REST API by using Chunked transfer encoding. We will get to know it in another article. Below are other related articles for your references:

OkHttp Post Examples

Java REST Client Examples Using OkHttp

Basic Authentication with OkHttp Example

Download a File with OkHttp

Set Timeout with OkHttp

WebSocket Client Example with OkHttp

 

 

 

 

 

0 0 vote
Article Rating