Convert Figma logo to code with AI

square logookhttp

Square’s meticulous HTTP client for the JVM, Android, and GraalVM.

45,699
9,144
45,699
175

Top Related Projects

3,378

Asynchronous Http and WebSocket Client library for Java

43,026

A type-safe HTTP client for Android and the JVM

An asynchronous, callback-based Http client for Android built on top of Apache's HttpClient libraries.

Listen to current network traffic in the app and categorize the quality of the network.

πŸš€ A Complete Fast Android Networking Library that also supports HTTP/2 πŸš€

Quick Overview

OkHttp is a modern, efficient HTTP client for Android and Java applications. It supports HTTP/2, allowing all requests to the same host to share a socket, and offers features like connection pooling, transparent GZIP compression, and response caching to improve network performance.

Pros

  • Automatic connection pooling and reuse, reducing latency for subsequent requests
  • Built-in support for HTTP/2 and SPDY protocols
  • Robust handling of network problems with automatic retries and fallbacks
  • Interceptors for monitoring, rewriting, and retrying calls

Cons

  • Steeper learning curve compared to simpler HTTP clients
  • May be overkill for simple API requests or small projects
  • Requires careful management of resources in long-running applications
  • Limited built-in support for more advanced authentication methods

Code Examples

  1. Making a simple GET request:
OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder()
    .url("https://api.example.com/data")
    .build();

try (Response response = client.newCall(request).execute()) {
    System.out.println(response.body().string());
}
  1. POST request with JSON payload:
MediaType JSON = MediaType.get("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();

String json = "{\"key\":\"value\"}";
RequestBody body = RequestBody.create(json, JSON);
Request request = new Request.Builder()
    .url("https://api.example.com/post")
    .post(body)
    .build();

try (Response response = client.newCall(request).execute()) {
    System.out.println(response.body().string());
}
  1. Using an interceptor for logging:
OkHttpClient client = new OkHttpClient.Builder()
    .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
    .build();

Request request = new Request.Builder()
    .url("https://api.example.com/data")
    .build();

try (Response response = client.newCall(request).execute()) {
    // The request and response will be logged
    System.out.println(response.body().string());
}

Getting Started

To use OkHttp in your project, add the following dependency to your build file:

For Gradle:

implementation("com.squareup.okhttp3:okhttp:4.10.0")

For Maven:

<dependency>
  <groupId>com.squareup.okhttp3</groupId>
  <artifactId>okhttp</artifactId>
  <version>4.10.0</version>
</dependency>

Then, create an OkHttpClient instance and use it to make HTTP requests:

OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder()
    .url("https://api.example.com/data")
    .build();

try (Response response = client.newCall(request).execute()) {
    System.out.println(response.body().string());
}

Competitor Comparisons

3,378

Pros of Volley

  • Built-in support for request prioritization and cancellation
  • Easier to use for simple network operations without additional configuration
  • Automatic scheduling of network requests

Cons of Volley

  • Less performant for large data transfers (e.g., downloading large files)
  • Limited customization options compared to OkHttp
  • Lack of modern features like HTTP/2 support

Code Comparison

Volley:

RequestQueue queue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                // Handle response
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // Handle error
            }
        });
queue.add(stringRequest);

OkHttp:

OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
    .url(url)
    .build();
client.newCall(request).enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        // Handle failure
    }
    @Override
    public void onResponse(Call call, Response response) throws IOException {
        // Handle response
    }
});

Both libraries offer easy-to-use APIs for making network requests, but OkHttp provides more flexibility and modern features, while Volley excels in simplicity for basic operations and request management.

Asynchronous Http and WebSocket Client library for Java

Pros of async-http-client

  • Supports both synchronous and asynchronous operations
  • Offers more advanced features like WebSocket support and streaming
  • Provides a wider range of configuration options for fine-tuning

Cons of async-http-client

  • Steeper learning curve due to more complex API
  • Less active maintenance and community support
  • Larger library size and potential for more dependencies

Code Comparison

async-http-client:

AsyncHttpClient client = new AsyncHttpClient();
Future<Response> f = client.prepareGet("http://www.example.com/").execute();
Response r = f.get();

OkHttp:

OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
    .url("http://www.example.com/")
    .build();
Response response = client.newCall(request).execute();

Summary

While async-http-client offers more advanced features and flexibility, OkHttp provides a simpler API and better maintenance. OkHttp is generally recommended for most Android projects due to its ease of use and strong community support. However, async-http-client may be preferred for projects requiring specific advanced features or more granular control over HTTP operations.

43,026

A type-safe HTTP client for Android and the JVM

Pros of Retrofit

  • Higher-level abstraction for API calls, simplifying network requests
  • Annotation-based interface definition for cleaner, more readable code
  • Built-in support for various converters (JSON, XML, etc.) and adapters

Cons of Retrofit

  • Steeper learning curve for beginners compared to OkHttp's simpler approach
  • Less flexibility for complex custom network operations
  • Requires additional setup and dependencies for full functionality

Code Comparison

Retrofit:

public interface GitHubService {
  @GET("users/{user}/repos")
  Call<List<Repo>> listRepos(@Path("user") String user);
}

GitHubService service = retrofit.create(GitHubService.class);
Call<List<Repo>> repos = service.listRepos("octocat");

OkHttp:

OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
    .url("https://api.github.com/users/octocat/repos")
    .build();
Response response = client.newCall(request).execute();

Retrofit builds on top of OkHttp, providing a more structured approach to API interactions. While OkHttp offers lower-level control, Retrofit simplifies the process of defining and making API calls. The choice between the two depends on the specific needs of the project and the developer's preference for abstraction level.

An asynchronous, callback-based Http client for Android built on top of Apache's HttpClient libraries.

Pros of android-async-http

  • Simpler API for basic HTTP requests
  • Built-in support for asynchronous callbacks
  • Easier to use for developers new to Android networking

Cons of android-async-http

  • Less actively maintained compared to OkHttp
  • Limited features for advanced use cases
  • Lacks modern HTTP/2 support

Code Comparison

android-async-http:

AsyncHttpClient client = new AsyncHttpClient();
client.get("https://api.example.com", new AsyncHttpResponseHandler() {
    @Override
    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
        // Handle success
    }
});

OkHttp:

OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
    .url("https://api.example.com")
    .build();
client.newCall(request).enqueue(new Callback() {
    @Override
    public void onResponse(Call call, Response response) throws IOException {
        // Handle response
    }
});

Summary

While android-async-http offers a simpler API for basic HTTP requests and is easier for beginners, OkHttp provides more advanced features, better performance, and active maintenance. OkHttp supports modern HTTP protocols and offers more flexibility for complex networking scenarios. For new Android projects, OkHttp is generally recommended due to its robust feature set and ongoing development.

Listen to current network traffic in the app and categorize the quality of the network.

Pros of network-connection-class

  • Specialized for network quality detection and classification
  • Provides real-time network quality information
  • Lightweight and focused on a specific use case

Cons of network-connection-class

  • Limited scope compared to OkHttp's full HTTP client functionality
  • Less active development and community support
  • May require additional libraries for complete HTTP functionality

Code Comparison

network-connection-class:

ConnectionClassManager.getInstance().register(mListener);
DeviceBandwidthSampler.getInstance().startSampling();

OkHttp:

OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
  .url("https://api.example.com")
  .build();
Response response = client.newCall(request).execute();

Summary

network-connection-class is a specialized library for network quality detection, offering real-time information about connection speeds. It's lightweight and focused on this specific use case. However, it has a more limited scope compared to OkHttp, which is a full-featured HTTP client.

OkHttp provides a comprehensive set of tools for making HTTP requests, handling responses, and managing connections. It offers more flexibility and features for general HTTP operations but doesn't specifically focus on network quality detection.

The choice between these libraries depends on the specific needs of your project. If you primarily need network quality information, network-connection-class might be suitable. For general HTTP operations, OkHttp is likely the better choice due to its broader feature set and active community support.

πŸš€ A Complete Fast Android Networking Library that also supports HTTP/2 πŸš€

Pros of Fast-Android-Networking

  • Simplified API for common networking tasks
  • Built-in support for caching and image loading
  • Easy request cancellation and prioritization

Cons of Fast-Android-Networking

  • Less flexible for advanced use cases
  • Smaller community and ecosystem compared to OkHttp
  • May have a steeper learning curve for developers familiar with OkHttp

Code Comparison

Fast-Android-Networking:

AndroidNetworking.get("https://api.example.com/data")
    .addQueryParameter("param", "value")
    .setPriority(Priority.MEDIUM)
    .build()
    .getAsJSONObject(new JSONObjectRequestListener() {
        @Override
        public void onResponse(JSONObject response) {
            // Handle response
        }
    });

OkHttp:

OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
    .url("https://api.example.com/data?param=value")
    .build();
client.newCall(request).enqueue(new Callback() {
    @Override
    public void onResponse(Call call, Response response) throws IOException {
        // Handle response
    }
});

Fast-Android-Networking provides a more concise API for common tasks, while OkHttp offers greater flexibility and control over the networking process. Fast-Android-Networking includes built-in features like caching and image loading, which may require additional libraries when using OkHttp. However, OkHttp's larger ecosystem and community support make it a more versatile choice for complex networking requirements.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

OkHttp

See the project website for documentation and APIs.

HTTP is the way modern applications network. ItҀ™s how we exchange data & media. Doing HTTP efficiently makes your stuff load faster and saves bandwidth.

OkHttp is an HTTP client thatҀ™s efficient by default:

  • 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 perseveres when the network is troublesome: it will silently recover from common connection problems. If your service has multiple IP addresses, OkHttp will attempt alternate addresses if the first connect fails. This is necessary for IPv4+IPv6 and services hosted in redundant data centers. OkHttp supports modern TLS features (TLS 1.3, ALPN, certificate pinning). It can be configured to fall back for broad connectivity.

Using OkHttp is easy. Its request/response API is designed with fluent builders and immutability. It supports both synchronous blocking calls and async calls with callbacks.

Get a URL

This program downloads a URL and prints its contents as a string. Full source.

OkHttpClient client = new OkHttpClient();

String run(String url) throws IOException {
  Request request = new Request.Builder()
      .url(url)
      .build();

  try (Response response = client.newCall(request).execute()) {
    return response.body().string();
  }
}

Post to a Server

This program posts data to a service. Full source.

public static final MediaType JSON = MediaType.get("application/json");

OkHttpClient client = new OkHttpClient();

String post(String url, String json) throws IOException {
  RequestBody body = RequestBody.create(json, JSON);
  Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
  try (Response response = client.newCall(request).execute()) {
    return response.body().string();
  }
}

Further examples are on the OkHttp Recipes page.

Requirements

OkHttp works on Android 5.0+ (API level 21+) and Java 8+.

OkHttp depends on Okio for high-performance I/O and the Kotlin standard library. Both are small libraries with strong backward-compatibility.

We highly recommend you keep OkHttp up-to-date. As with auto-updating web browsers, staying current with HTTPS clients is an important defense against potential security problems. We track the dynamic TLS ecosystem and adjust OkHttp to improve connectivity and security.

OkHttp uses your platform's built-in TLS implementation. On Java platforms OkHttp also supports Conscrypt, which integrates BoringSSL with Java. OkHttp will use Conscrypt if it is the first security provider:

Security.insertProviderAt(Conscrypt.newProvider(), 1);

The OkHttp 3.12.x branch supports Android 2.3+ (API level 9+) and Java 7+. These platforms lack support for TLS 1.2 and should not be used.

Releases

Our change log has release history.

The latest release is available on Maven Central.

implementation("com.squareup.okhttp3:okhttp:4.12.0")

Snapshot builds are available. R8 and ProGuard rules are available.

Also, we have a bill of materials (BOM) available to help you keep OkHttp artifacts up to date and be sure about version compatibility.

    dependencies {
       // define a BOM and its version
       implementation(platform("com.squareup.okhttp3:okhttp-bom:4.12.0"))

       // define any required OkHttp artifacts without version
       implementation("com.squareup.okhttp3:okhttp")
       implementation("com.squareup.okhttp3:logging-interceptor")
    }

MockWebServer

OkHttp includes a library for testing HTTP, HTTPS, and HTTP/2 clients.

The latest release is available on Maven Central.

testImplementation("com.squareup.okhttp3:mockwebserver:4.12.0")

GraalVM Native Image

Building your native images with Graal https://www.graalvm.org/ should work automatically. This is not currently in a final released version, so 5.0.0-alpha.2 should be used. Please report any bugs or workarounds you find.

See the okcurl module for an example build.

$ ./gradlew okcurl:nativeImage
$ ./okcurl/build/graal/okcurl https://httpbin.org/get

License

Copyright 2019 Square, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.