简介
HTTP 是现代应用程序网络的方式。这就是我们交换数据和媒体的方式。有效地执行 HTTP 可以使您的内容加载速度更快并节省带宽。
OkHttp 是一个默认高效的 HTTP 客户端:
- HTTP/2 支持允许对同一主机的所有请求共享一个套接字。
- 连接池减少了请求延迟(如果 HTTP/2 不可用)。
- 透明 GZIP 可缩小下载大小。
- 响应缓存完全避免网络重复请求。
官网地址:https://square.github.io/okhttp/
前置准备
1.pom中引入依赖
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.0</version>
</dependency>
2.创建实例
方法1:默认的构造方法:OkHttpClient client = new OkHttpClient();
方法2:这种方式支持用户自定义参数设置,比如日志拦截器,设置缓存目录和大小等参数。
public final OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new HttpLoggingInterceptor())
.cache(new Cache(cacheDir, cacheSize))
.build();
方法3:如果要求使用现有的实例,可以通过newBuilder()方法来进行构造。
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)//设置连接超时时间
.readTimeout(30, TimeUnit.SECONDS)//设置读取超时时间
.build();
使用(以下贴例子)
发现一篇写的很好的文章:https://blog.csdn.net/jiaonizuoren/article/details/89915198
1.get请求,同步请求(execute()方法)
public class okttpTest {
public static void main(String[] args) throws IOException {
OkHttpClient client = new OkHttpClient();
String url = "http://www.baidu.com";
Request request = new Request.Builder().url(url).method("GET", null).build();
Response response = client.newCall(request).execute();
String json = response.body().string();
System.out.println(request);
System.out.println(response.code());
System.out.println(response);
}
}
输出如下;
2. get请求,异步请求(execute()方法)
Request request = new Request.Builder()
.url("http://publicobject.com/helloworld.txt")
.build();
client.newCall(request).enqueue(new Callback(){
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
Headers responseHeaders = response.headers();
for (int i = 0; i < responseHeaders.size(); i++) {
System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
}
System.out.println(response.body().string());
}
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
e.printStackTrace();
}
});
总结
Get:
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:
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();
}
}