OkHttp

作者: sys1211 | 来源:发表于2017-04-02 09:39 被阅读3次

概述

HTTP是现代应用网络的方式。这是我们如何交换数据和媒体。有效地进行HTTP使您的东西加载更快,并节省带宽。

OkHttp是默认情况下高效的HTTP客户端

HTTP / 2支持允许同一主机的所有请求共享套接字。

连接池减少请求延迟(如果HTTP / 2不可用)。

透明GZIP缩小下载大小。

响应缓存可以避免重复请求的网络。

当网络麻烦时,OkHttp坚持不懈:它将从常见的连接问题中静默地恢复。如果您的服务有多个IP地址,如果第一个连接失败,OkHttp将尝试替代地址。这对于IPv4 + IPv6以及在冗余数据中心中托管的服务是必需的。OkHttp启动与现代TLS功能(SNI,ALPN)的新连接,如果握手失败,则返回TLS 1.0。

使用OkHttp很容易它的请求/响应API设计有流畅的构建器和不变性。它支持同步阻塞调用和具有回调的异步调用。

OkHttp支持Android 2.3及以上版本。对于Java,最低要求是1.7。


例子

获取网址

该程序下载URL并将其内容作为字符串打印。

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();

}

}

public static void main(String[] args) throws IOException {

GetExample example = new GetExample();

String response = example.run("https://raw.github.com/square/okhttp/master/README.md");

System.out.println(response);

}

发布到服务器

该程序将数据发送到服务。

public static final MediaType JSON

= MediaType.parse("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();

相关文章

网友评论

    本文标题:OkHttp

    本文链接:https://www.haomeiwen.com/subject/utxgottx.html