In previous posts we figured out how to send Http requests and get Http responses with Apache HttpComponents and RESTEasy
Today we’re going to have some fun with OkHttp.
OkHttp Maven dependency
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.11.0</version>
</dependency>
GET request example
Now we have to instantiate OkHttpClient
OkHttpClient client = new OkHttpClient();
and build Request
.
String url = "https://user-service.mycompany.com";
Request request = new Request.Builder()
.url(url)
.build();
If we need to add a Http Header
Request request = new Request.Builder()
.addHeader("Accept", "application/json")
.url(url)
.build();
POST request example
For POST the request will be
RequestBody body = RequestBody
.create(MediaType.parse("application/json"), jsonString);
Request request = new Request.Builder()
.post(body)
.addHeader("Accept", "application/json")
.url(url)
.build();
PUT request example
RequestBody body = RequestBody.create(MediaType
.parse("application/json"), jsonString);
Request request = new Request.Builder()
.put(body)
.addHeader("Accept", "application/json")
.url(url)
.build();
DELETE request example
RequestBody body = RequestBody
.create(MediaType.parse("application/json"), jsonString);
Request request = new Request.Builder()
.delete()
.addHeader("Accept", "application/json")
.url(url)
.build();
Http Response
Now we can make a call and get the Http response
Response response = client.newCall(request).execute();
The response body as a string
String responseBody = response.body().string();
The response body to the object
Gson gson = new Gson();
User user = gson.fromJson(responseBody, User.class);
See more about How to convert JSON to Java Object.
The response code
int responseCode = response.code();
That’s pretty much it.
OkHttp is the easy to use Http client that covers most of basic needs
You may also find these posts interesting: