概述
okhttp 官网:https://square.github.io/okhttp/
HTTP是现代应用网络的方式。这就是我们交换数据和媒体的方式。有效地执行HTTP可以加快您的负载并节省带宽。
OkHttp是一个默认有效的HTTP客户端:
- HTTP / 2支持允许对同一主机的所有请求共享套接字。
- 连接池减少了请求延迟(如果HTTP / 2不可用)。
- 透明GZIP缩小了下载大小。
- 响应缓存完全避免网络重复请求。
当网络很麻烦时,OkHttp坚持不懈:它将从常见的连接问题中无声地恢复。如果您的服务有多个IP地址,如果第一次连接失败,OkHttp将尝试备用地址。这对于IPv4 + IPv6和冗余数据中心中托管的服务是必需的。OkHttp启动具有现代TLS功能(SNI,ALPN)的新连接,并在握手失败时回退到TLS 1.0。
使用OkHttp很简单。它的请求/响应API采用流畅的构建器和不变性设计。它支持同步阻塞调用和带回调的异步调用。
本文只是简单的试用一下,两个小demo。
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.11.0</version>
</dependency>
get请求
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
public class GetExample {
OkHttpClient client = new OkHttpClient();//创建okhttp客户端
String run(String url) throws IOException {
//创建request
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 okhttp3.*;
import java.io.IOException;
public class PostExample {
//指定请求头,json格式
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);
//创建requestbody
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
//同步执行请求
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
//拼接json格式参数
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);
}
}
同步/异步请求
上面两个实例都是同步请求,下面看看异步请求如何编写:
//异步请求
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
System.out.println(e.getMessage());
}
@Override
public void onResponse(Call call, okhttp3.Response response) throws IOException {
String string = response.body().string();
System.out.println(string);
}
});