OkHttp官方教程

简介: OkHttp官方教程

OkHttp

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; charset=utf-8");
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 on 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. But because upgrading is difficult we will backport critical fixes to the 3.12.x branch            through December 31, 2020.


Releases

Our change log has release history.

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

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


MockWebServer

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

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

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.


目录
相关文章
|
JSON 数据格式
okhttp3 模拟get、post(json参数传递,form表单提交)
本文是博主学习okhttp3 的记录,希望对大家有所帮助。
3680 0
|
自然语言处理 前端开发 Java
API管理平台:你用的到底是哪个?
本文介绍了多个API管理和文档工具,包括Apifox、Swagger及其增强版Knife4j和RapiDoc、阿里RAP、去哪儿YApi以及Redoc。这些工具各有特色,适用于不同的开发场景。Apifox提供一体化协作平台,支持API文档、调试、Mock和测试;Swagger结合Knife4j适合Java与前端团队,界面美观且功能丰富;YApi则适用于跨语言开发,支持多种API形式的管理;阿里RAP专注于接口文档管理和Mock服务;Redoc则是开源的现代化API文档浏览器。总结而言,选择工具应根据团队需求和技术栈来决定。
5866 16
|
人工智能 弹性计算 运维
通勤路上修故障?钉钉机器人+OOS AI助手实现7×24小时运维自由
通过钉钉机器人配置阿里云OOS AI助手,您可以直接在钉钉群内发送文字指令,实现免登录、跨设备、秒级响应的阿里云运维操作。
|
Java Android开发 开发者
Android Studio Profiler Memory (内存分析工具)的简单使用及问题分析
Android Studio Profiler Memory (内存分析工具)的简单使用及问题分析
4235 0
Android Studio Profiler Memory (内存分析工具)的简单使用及问题分析
|
消息中间件 存储 RocketMQ
2分钟看懂RocketMQ延迟消息核心原理
本文从源码层面解析了RocketMQ延迟消息的实现原理,包括延迟消息的使用、Broker端处理机制以及定时任务对延迟消息的处理流程。
2分钟看懂RocketMQ延迟消息核心原理
|
敏捷开发 数据库 微服务
SpringCloud微服务拆分原则
SpringCloud微服务拆分原则
707 2
|
存储 安全 数据库
对称加密的日常实践应用:以AES为例的加密解密指南
**摘要:** 本文介绍了对称加密算法AES在数据安全中的应用,强调了其在文件、通信和数据库加密中的重要性。通过Python示例展示了如何使用`cryptography`库实现AES-256的加密和解密,涉及密钥生成、CBC模式及PKCS7填充。同时,提醒注意密钥管理、模式选择和填充方式的选择对加密安全性的影响。
2298 1
|
缓存 Java API
OKHttp详解
OKHttp详解