랭킹으로 돌아가기

lysine-dev/okhttp

Kotlinlysine.dev/okhttp/

A meticulous HTTP client for the JVM, Android, and GraalVM.

javaandroidkotlingraalvm
스타 성장
스타
47k
포크
9.3k
주간 성장
이슈
86
20k40k
2012년 9월2017년 4월2021년 12월2026년 7월
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.

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

  • Does not allow GET with a body.
  • Cache is not an interface with alternative implementations.

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.4.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.4.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.4.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:

  • okhttp3
  • okhttp3.brotli
  • okhttp3.coroutines
  • okhttp3.dnsoverhttps
  • okhttp3.java.net.cookiejar
  • okhttp3.logging
  • okhttp3.sse
  • okhttp3.tls
  • okhttp3.urlconnection
  • mockwebserver3
  • mockwebserver3.junit4
  • mockwebserver3.junit5

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.
관련 저장소
CyC2018/CS-Notes

:books: 技术面试必备基础知识、Leetcode、计算机操作系统、计算机网络、系统设计

algorithmleetcode
cyc2018.xyz
184.8k50.8k
Snailclimb/JavaGuide

Java 面试 & 后端通用面试指南,覆盖计算机基础、数据库、分布式、高并发、系统设计与 AI 应用开发

JavaScriptnpmApache License 2.0javainterview
javaguide.cn
157.2k46.2k
iluwatar/java-design-patterns

Design patterns implemented in Java

JavaMavenOtherjavaprinciples
java-design-patterns.com
94.2k27.4k
Stirling-Tools/Stirling-PDF

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

JavaMavenOtherdockerjava
stirling.com
87.5k7.7k
macrozheng/mall

mall项目是一套电商系统,包括前台商城系统及后台管理系统,基于Spring Boot+MyBatis实现,采用Docker容器化部署。 前台商城系统包含首页门户、商品推荐、商品搜索、商品展示、购物车、订单流程、会员中心、客户服务、帮助中心等模块。 后台管理系统包含商品管理、订单管理、会员管理、促销管理、运营管理、内容管理、统计报表、财务管理、权限管理、设置等模块。

JavaMavenApache License 2.0spring-bootspring-security
macrozheng.com/admin/
84.3k29.8k
spring-projects/spring-boot

Spring Boot helps you to create Spring-powered, production-grade applications and services with absolute minimum fuss.

JavaMavenApache License 2.0javaspring-boot
spring.io/projects/spring-boot
81.1k42k
doocs/advanced-java

😮 Core Interview Questions & Answers For Experienced Java(Backend) Developers | 互联网 Java 工程师进阶知识完全扫盲:涵盖高并发、分布式、高可用、微服务、海量数据处理等领域知识

JavaMavenCreative Commons Attribution Share Alike 4.0 Internationaljavadistributed-systems
java.doocs.org
79k19.2k
elastic/elasticsearch

Free and Open Source, Distributed, RESTful Search Engine

JavaMavenOtherelasticsearchjava
elastic.co/products/elasticsearch
77.6k26.1k
TheAlgorithms/Java

All Algorithms implemented in Java

JavaMavenMIT Licensejavaalgorithms
66k21.2k
kdn251/interviews

Everything you need to know to get the job.

JavaMavenMIT Licensejavainterview
youtube.com/channel/UCKvwPt6BifPP54yzH99ff1g
65.1k12.9k
youngyangyang04/leetcode-master

《代码随想录》LeetCode 刷题攻略:200道经典题目刷题顺序,共60w字的详细图解,视频难点剖析,50余张思维导图,支持C++,Java,Python,Go,JavaScript等多语言版本,从此算法学习不再迷茫!🔥🔥 来看看,你会发现相见恨晚!🚀

Shellleetcodeprogrammer
62k12.3k
azl397985856/leetcode

LeetCode Solutions: A Record of My Problem Solving Journey.( leetcode题解,记录自己的leetcode解题之路。)

JavaScriptnpmOtheralgorithmleetcode
leetcode-solution-leetcode-pp.gitbook.io/leetcode-solution/
55.8k9.4k