In this post I will explain to you how we can send GET And POST request using OKHttp in Android Application. In my last post, I will explain how we can send GET and Post Request using Volley. OKHttp and Http & Http/2 client is widely used in android and java applications to create a request to the server. In this post, I am going to explain some most useful feature of OKHttp.

OKHttp is the modern way to make and exchange data and media over HTTP network. It helps to load data faster, efficiently and also saves bandwidth.

  • HTTP/2 support allows all requests to the same host to share a socket.
  • Connection pooling reduces request latency (if HTTP/2 isn’t available).
  • Transparent GZIP shrinks download sizes.
  • Response caching avoids the network completely for repeat requests.

OkHttp is very easy to use. Its request/response API is designed with fluent builders and immutability. It supports both synchronous blocking calls and async calls with callbacks. Now we can start creating our android application.

Step 1. Create a new Android project in Android Studio and name it what you like.

Step 2. Now we need to add dependencies to our Android project add below code and sync

Step 3. Add internet permission in manifest file

Now I can create a simple method in which In which I can explain how we can use OkHttp to send the request.

When we call above method it returns a list of the user. This method makes an Asynchronous call to the server because if you make the Synchronous call using Response method it will through NetworkOnMainThread exception on response.body() error so I prefer to use Async call.

In above method, I also add header because in my server API it is required to send header type and it is very easy in OKHttp to set header and Auth Token in it I further explain how to do that. And also to make Async call we need to add newCall() and enqueue() to run and get callback response in it.

Step 4. In this step, I will explain to you how we can post data to the server in OKHttp if you want to send get request please check function in Step 3 I created. To create a post request we need to create a JSON Object and after that, we need to convert JSON to string and post it to the server it was a very easy task.

Above method is same as we create method on step 3 but in this, we create JSON Object and pass that object to RequestBody and the add RequestBody in post method where we create actual request.

 

Complete Code of OKHttp Example:-

GET And POST request using OKHttp Android

Screen Layout Code

Here is MainActivity Code

Note please change username and password when you run this example.

Hope this post helps you 🙂