深入理解OkHttp3:(一)综述

OkHttp是用于Android和Java应用程序的HTTP & HTTP2客户端框架。

HTTP是现代应用程序网络通讯的协议。这是我们交换数据的常用方式。合理的使用HTTP将使您的内容加载速度更快,并节省带宽。

OkHttp通过以下方式来做到高效:

1,支持HTTP/2,允许对同一主机的所有请求共享一个套接字。
2,采用连接池,减少了请求延迟(HTTP/2不可用)。
3,透明GZIP压缩,节省了带宽。
4,结果缓存,完全避免了网络对重复请求的访问。

当网络不好的时候,OkHttp会帮你坚持不懈的努力加载: 它会从常见的连接问题中默默的恢复。如果您的服务有多个IP地址,那么如果第一次连接失败,OkHttp将尝试替换地址。这对于IPv4+IPv6和冗余数据中心中托管的服务是必要的。OkHttp启动了与现代TLS特性(SNI、ALPN)的新连接,如果握手失败,则返回到TLS 1.0。

使用OkHttp很容易。它的请求/响应API是用连贯的构建器模式和不变性来设计的。它支持同步阻塞调用和带有回调的异步调用。

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

例子:

Get方式获取数据并打印:

import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class GetExample {
  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);
  }
}

Post数据到服务器:

import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class PostExample {
  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();
    }
  }
  String bowlingJson(String player1, String player2) {
    return "{'winCondition':'HIGH_SCORE',"
        + "'name':'Bowling',"
        + "'round':4,"
        + "'lastSaved':1367702411696,"
        + "'dateStarted':1367702378785,"
        + "'players':["
        + "{'name':'" + player1 + "','history':[10,8,6,7,8],'color':-13388315,'total':39},"
        + "{'name':'" + player2 + "','history':[6,10,5,10,10],'color':-48060,'total':41}"
        + "]}";
  }
  public static void main(String[] args) throws IOException {
    PostExample example = new PostExample();
    String json = example.bowlingJson("Jesse", "Jake");
    String response = example.post("http://www.roundsapp.com/post", json);
    System.out.println(response);
  }
}

使用:

Maven:

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

Gradle:

compile 'com.squareup.okhttp3:okhttp:3.2.0'

本文为翻译文章:原文地址:https://square.github.io/okhttp/

猜你喜欢

转载自blog.csdn.net/challenge51all/article/details/82835807
今日推荐