A modern HTTP client for Android and Java applications.

Apache-2.0

Quick Start

Setup Steps

  1. Add the OkHttp dependency to your build.gradle file.
  2. Sync your project with Gradle.
  3. Create an OkHttpClient instance and make requests.

Overview

OkHttp is an efficient HTTP & HTTP/2 client for Android and Java applications. It simplifies network calls, handles connection pooling, and supports modern protocols.

Features

HTTP/2 and HTTP/1.1 support
Connection pooling for reduced latency
Transparent GZIP compression
Response caching to avoid network calls
WebSocket support for real-time communication
Easy interceptors for request/response manipulation

Use Cases

Making REST API calls in Android apps
Downloading files or images
Implementing WebSocket clients
Testing network-related code

When Not to Use

For extremely simple HTTP requests where HttpURLConnection is sufficient
When trying to minimize app size and dependencies
For non-JVM platforms without appropriate wrappers

Usage Examples

Synchronous GET Request
val client = OkHttpClient()
val request = Request.Builder()
    .url("https://api.example.com/data")
    .build()
val response = client.newCall(request).execute()

Basic example of a synchronous HTTP GET request.

Asynchronous Request with Callback
val call = client.newCall(request)
call.enqueue(object : Callback {
    override fun onFailure(call: Call, e: IOException) {
        // Handle error
    }
    override fun onResponse(call: Call, response: Response) {
        // Handle response
    }
})

Making an asynchronous call using callbacks.

Common Pitfalls

  • Not closing Response bodies can lead to memory leaks.
  • Mixing synchronous and asynchronous calls improperly.
  • Forgetting to handle network exceptions and timeouts.
  • Not using interceptors for logging or authentication when needed.

Integration

Works well with

Retrofit for type-safe REST API interfacesMoshi or Gson for JSON serializationKotlin Coroutines for structured concurrencyGlide or Picasso for image loading with network
  • OkHttp is often used as the HTTP client for Retrofit.
  • Ensure to add proper proguard rules if using in release builds.
  • Interceptors can be added for logging, authentication, etc.

Alternatives

HttpURLConnection

Built-in to Java, no external dependencies, suitable for very simple use cases.

Volley

Google's HTTP library for Android, optimized for image loading and request prioritization.

Fuel

Kotlin-first HTTP client with a more concise API, but less mature than OkHttp.

Maintenance & Health

  • Latest version is not specified; please check the official repository for the most recent release.
  • Maven coordinates and SDK versions may vary; refer to the documentation for accurate information.

Related libraries