This tutorial is going to cover about how to post with OkHttp, an HTTP & HTTP/2 client for Android and Java applications. We’re going to get though some popular use cases and examples such as how to post a string, how to post a form, how to post a stream and so on.
1. Preparation
We’re going to use OkHttp, version 3.5.0 for all OkHttp post examples in the tutorial, and the only Maven dependency we will need is:
1 2 3 4 5 |
<dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>3.5.0</version> </dependency> |
2. Post a String with OkHttp
Let’s see a following example which we will post a string with OkHttp using OkHttpClient.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
@Test public void testPostingWithString() throws IOException { OkHttpClient client = new OkHttpClient.Builder().build(); MediaType textPlainMT = MediaType.parse("text/plain; charset=utf-8"); String helloMsg = "Hello OkHttp"; Request request = new Request.Builder().url("http://httpbin.org/post") .post(RequestBody.create(textPlainMT, helloMsg)).build(); Response response = client.newCall(request).execute(); assertTrue(response.isSuccessful()); response.close(); } |
In the example, after creating the client, we create a request by providing the builder the URL of the remote endpoint, the HTTP Post method and the request body. Note how we created the request body by providing the text we want to post and its media type.
Because the entire request body is in memory simultaneously, we should avoid posting large (greater than 1 MiB) documents using this API.
3. Post a Byte Array
It’s easy to post a byte array with OkHttp. Following is an example that we will post a byte array to a RESTful web service.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
private static final MediaType MEDIA_TYPE_PLAINTEXT = MediaType .parse("text/plain; charset=utf-8"); private final OkHttpClient client = new OkHttpClient(); @Test public void testPostByteArray() throws Exception { String st = "posting a byte array with OkHttp"; Request request = new Request.Builder() .url("http://httpbin.org/post") .post(RequestBody.create(MEDIA_TYPE_PLAINTEXT, st.getBytes("UTF8"))) .build(); Response response = client.newCall(request).execute(); assertTrue(response.isSuccessful()); } |
4. Post Form Parameters
OkHttp allows us to post form parameters by using FormBody.Builder to build a request body that works like an HTML <form> tag. Names and values will be encoded using an HTML-compatible form URL encoding. Let’s see an example which we will post form parameters with OkHttp using OkHttpClient.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
private final OkHttpClient client = new OkHttpClient(); @Test public void testPostForm() throws Exception { RequestBody formBody = new FormBody.Builder() .add("email", "user@howtoprogram.xyz") .add("firstname", "John").add("lastname", "Henry").build(); Request request = new Request.Builder().url("http://httpbin.org/post") .post(formBody) .build(); Response response = client.newCall(request).execute(); assertTrue(response.isSuccessful()); } |
In the example, we have just used the FormBody.builder to create a form with 3 fields: email, firstname, lastname and then posted the form to the remote URL.
5. Post a File
It’s pretty simple to post a file with OkHttp. We can use the RequestBody class to create a request body that transmits the content of a file. Let’s see the following example which we will post a file using OkHttpClient:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
private static final MediaType MEDIA_TYPE_PLAINTEXT = MediaType .parse("text/plain; charset=utf-8"); private final OkHttpClient client = new OkHttpClient(); @Test public void testPostFile() throws Exception { File file = new File("src/test/resources/Lorem Ipsum.txt"); Request request = new Request.Builder() .url("http://httpbin.org/post") .post(RequestBody.create(MEDIA_TYPE_PLAINTEXT, file)) .build(); Response response = client.newCall(request).execute(); assertTrue(response.isSuccessful()); } |
In the above example, we have posted the Lorem Ipsum.txt file to a RESTful web service.
6. Post a Stream
With OkHttp, we can POST a request body as a stream. The content of this request body is being generated as it’s being written. Let’s see an example which we will post a stream to a REST API.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
private static final MediaType MEDIA_TYPE_PLAINTEXT = MediaType .parse("text/plain; charset=utf-8"); private final OkHttpClient client = new OkHttpClient(); @Test public void testPostStream() throws Exception { RequestBody requestBody = new RequestBody() { @Override public MediaType contentType() { return MEDIA_TYPE_PLAINTEXT; } @Override public void writeTo(BufferedSink sink) throws IOException { File file = new File("src/test/resources/Lorem Ipsum.txt"); try (BufferedReader br = new BufferedReader(new FileReader(file))) { String line; while ((line = br.readLine()) != null) { sink.writeUtf8(line); } } } }; Request request = new Request.Builder() .url("http://httpbin.org/post") .post(requestBody) .build(); Response response = client.newCall(request).execute(); assertTrue(response.isSuccessful()); } |
In the example, we posted a stream by creating new RequestBody and overriding the writeTo method in which we read the file Lorem Ipsum.txt line by line and streamed into the buffered sink of the request.
7. Post a Multipart Request
We can use the MultipartBody.Builder class to build request bodies compatible with HML file upload forms. We can leverage this feature to upload files, images with OkHttp. Let’s see an example which we will post a multipart request to a RESTful web service.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
private static final MediaType MEDIA_TYPE_PLAINTEXT = MediaType .parse("text/plain; charset=utf-8"); private final OkHttpClient client = new OkHttpClient(); @Test public void testPostMultipart() throws IOException { File file = new File("src/test/resources/Lorem Ipsum.txt"); RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("file", "LoremIpsum.txt", RequestBody.create(MEDIA_TYPE_PLAINTEXT, file)) .addFormDataPart("description", "Just Lorem Ipsum") .build(); Request request = new Request.Builder() .url("http://httpbin.org/post") .post(requestBody).build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) { throw new IOException("Unexpected code " + response); } } |
In the example, we created an instance of the MultipartBody class which is a an RFC 2387-compliant request. Then we added a file part and a description part to the request body, and finally we execute the request to post the form to the RESTful web service.
8. Conclusion
The tutorial has showed us how to post with OkHttp in different ways and use cases from how to post a string, how to post a stream, how to post a Multipart request and so on.
The OkHttp post examples source code can be found on the Github project. It’s an Maven based project, so it’s easy to import and run it in any IDE such as Eclipse, Intellij, etc.
Below are other related tutorials for your references:
How to Cache Response with OkHttp
Java REST Client Examples Using OkHttp
Basic Authentication with OkHttp Example
WebSocket Client Example with OkHttp