okhttp README

The project's README from github.com/lysine-dev/okhttp. As one markdown file: README.md.

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:

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.

A well behaved user agent

OkHttp follows modern HTTP specifications such as

Where the spec is ambiguous, OkHttp follows modern user agents such as popular Browsers or common HTTP Libraries.

OkHttp is principled and avoids being overly configurable, especially when such configuration is to workaround a buggy server, test invalid scenarios or that contradict the relevant RFC. Other HTTP libraries exist that fill that gap allowing extensive customisation including potentially invalid requests.

Example Limitations

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+.

On Android, OkHttp uses AndroidX Startup. If you disable the initializer in the manifest, then apps are responsible for calling OkHttp.initialize(applicationContext) in Application.onCreate.

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:5.5.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:5.5.0"))

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

Maven and JVM Projects

OkHttp is published as a Kotlin Multiplatform project. While Gradle handles this automatically, Maven projects must select between okhttp-jvm and okhttp-android. The okhttp artifact will be empty in Maven projects.

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.squareup.okhttp3</groupId>
      <artifactId>okhttp-bom</artifactId>
      <version>5.2.0</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>
<dependency>
  <groupId>com.squareup.okhttp3</groupId>
  <artifactId>okhttp-jvm</artifactId>
  <!-- Remove after OkHttp 5.2.0 with updated BOM. -->
  <version>5.1.0</version>
</dependency>

<dependency>
  <groupId>com.squareup.okhttp3</groupId>
  <artifactId>mockwebserver3</artifactId>
</dependency>

<dependency>
  <groupId>com.squareup.okhttp3</groupId>
  <artifactId>logging-interceptor</artifactId>
</dependency>

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:mockwebserver3:5.5.0")

MockWebServer is used for firstly for internal testing, and for basic testing of apps using OkHttp client. It is not a full featured HTTP testing library that is developed standalone. It is not being actively developed for new features. As such you might find your needs outgrow MockWebServer and you may which to use a more full featured testing library such as MockServer.

GraalVM Native Image

Building your native images with GraalVM should work automatically.

See the okcurl module for an example build.

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

Java Modules

OkHttp (5.2+) implements Java 9 Modules.

With this in place Java builds should fail if apps attempt to use internal packages.

error: package okhttp3.internal.platform is not visible
    okhttp3.internal.platform.Platform.get();
                    ^
  (package okhttp3.internal.platform is declared in module okhttp3,
    which does not export it to module com.bigco.sdk)

The stable public API is based on the list of defined modules:

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.

okhttp (lysine-dev/okhttp)

Searching Database…

47.1K ·GitHub
Что это такое?OkHttp — это эффективный HTTP-клиент для JVM, Android и GraalVM, который работает с HTTP/1.1, HTTP/2, WebSocket и SSE, использует пул соединений и прозрачно сжимает данные через GZIP.
Это библиотека или самостоятельное приложение?Это библиотека, которую вы добавляете как зависимость в проект на Java, Kotlin или Android, а не отдельное приложение.
Как добавить это в проект?Подключите через Maven Central как зависимость Gradle или Maven; в проектах Maven нужно выбрать между okhttp-jvm и okhttp-android, потому что обычный артефакт okhttp там пустой.
Нужно ли что-то кроме самой библиотеки?Нужен Android 5.0+ (уровень API 21+) или Java 8+. OkHttp зависит от Okio и стандартной библиотеки Kotlin — обе они небольшие и хорошо сохраняют обратную совместимость.
Есть ли подводные камни при обновлении или использовании?Библиотека намеренно не предлагает обширных настроек (например, она не позволит отправить GET-запрос с телом), а на Android нужно либо оставить включённым инициализатор AndroidX Startup, либо вручную вызвать OkHttp.initialize() в Application.onCreate.
Одинаково ли это работает на старых версиях Android и Java?Основная линейка OkHttp рассчитана на Android 5.0+ и Java 8+ с современным TLS; устаревшая ветка 3.12.x поддерживает Android 2.3+ и Java 7+, но не имеет TLS 1.2 и не рекомендуется.
Что такое MockWebServer?Это входящая в состав библиотека для тестирования HTTP-, HTTPS- и HTTP/2-клиентов, которая в основном используется для внутренних тестов самого OkHttp и базового тестирования приложений; это не полноценный самостоятельный инструмент для тестирования и он больше не развивается активно.
Как OkHttp справляется с нестабильной сетью?Он незаметно восстанавливается после типичных проблем с соединением и, если у сервиса несколько IP-адресов, пробует альтернативные адреса, когда первая попытка подключения не удалась; это помогает при работе с IPv4 и IPv6 и с резервными дата-центрами.
Поддерживает ли он нативные образы GraalVM?Да, сборка нативных образов с GraalVM должна работать автоматически, а модуль okcurl приведён как пример сборки.
Какие возможности TLS он поддерживает?Он поддерживает современные возможности TLS, включая TLS 1.3, ALPN и закрепление сертификатов (certificate pinning), и при необходимости может откатываться к более старым вариантам для более широкой совместимости.
Creator
lysine-dev
Size
66.8 MB
Stars
47.1K
Updated
CommitOct 17
Age
14y
Commits · 90 Days