In this post, we will create an OkHttp PUT HTTP request example in Java.
OkHTTP is an open source project designed to be an efficient HTTP client for Android and Java applications.
OkHttp supports Android 5.0+ (API level 21+) and Java 1.8+. In this article, we will write a code using Java 1.8+.
Maven Dependency
Let’s first add the library as a dependency into the pom.xml:
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.9.0</version>
</dependency>
To see the latest dependency of this library check out the page on Maven Central.
In this post, we will create a PUT HTTP client for spring boot CRUD example project. This spring boot crud example project is deployed and up and running. Refer to this article - https://www.javaguides.net/2018/09/spring-boot-2-hibernate-5-mysql-crud-rest-api-tutorial.html
OkHttp PUT Request Java Example
In below example, we are updating an existing user object with the following details:
Update firstName = "Ramesh" -> "Ram"
Update emailId = "ramesh@gmail.com" -> "ram@gmail.com":
package com.javaguides.okhttp.tutorial.crud;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class OkHttpPut {
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder().url(url).put(body).build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
public static void main(String[] args) throws IOException {
OkHttpPut example = new OkHttpPut();
String json = "{\r\n" +
" \"firstName\" : \"Ram\",\r\n" +
" \"lastName\" : \"Fadatare\",\r\n" +
" \"emailId\" : \"ram@gmail.com\"\r\n" +
"}";
String response = example.post("http://localhost:8080/api/v1/employees/1", json);
System.out.println(response);
}
}
Below diagram shows the screenshot of source code as well as output:
Comments
Post a Comment
Leave Comment