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.
Discover DeepSeek R1, the free, open-source AI model that rivals GPT-4 in performance. Licensed under MIT, it’s cost-effective, efficient, and transforming the AI landscape. Try it now!
Looking for the best 5G phone under 20000 in India? Check out our top picks for 2025, featuring amazing performance, stunning cameras, and excellent battery life. Read now!
Discover whether blogging is profitable in 2025 and learn effective strategies to thrive in the digital age with AI tools, niche blogging, and modern monetization methods.
Discover the best smartphones under ₹20,000 in India (2025). From the gaming powerhouse Poco X6 Pro to the stylish Motorola Edge 50 Neo and the sleek Nothing Phone 2A, find the perfect phone for your needs.