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.
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
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.
Explore the best smartphones under ₹20,000 in 2025, featuring top picks for gaming, photography, and all-round performance. Compare specs, pros, and cons to find your perfect budget smartphone.
Discover the Xiaomi Pad 7’s sleek design, powerful Snapdragon 7+ Gen 3 performance, stunning display, and excellent gaming capabilities. Read our full review for the best tablet experience.
Discover the best tablets under ₹30,000 in 2025, including OnePlus Pad Go, Lenovo Tab P12, Redmi Pad Pro 5G, Xiaomi Pad 7, and Samsung Galaxy Tab S9 FE. Compare features, specifications, and performan