Fork me on GitHub

OkHttp3(1)

简介

翻译自官网

套话….

  • 支持http2,对一台机器的所有请求共享同一个socket
  • 内置连接池,支持连接复用,减少延迟
  • 支持透明的gzip压缩响应体
  • 通过缓存避免重复的请求
  • 请求失败时自动重试主机的其他备用ip,自动重定向
  • 好用的API

引入

implementation 'com.squareup.okhttp3:okhttp:3.10.0'

记得加上网络权限

基本使用

get请求

1
2
3
4
5
6
7
8
9
10
11
12
13
String url = "http://write.blog.csdn.net/postlist/0/0/enabled/1";
OkHttpClient okHttpClient = new OkHttpClient();

Request request = new Request.Builder().url(url).build();
okhttp3.Response response = null;
try {
response = okHttpClient.newCall(request).execute();
String json = response.body().string();
Log.i(TAG,json);

} catch (IOException e) {
e.printStackTrace();
}

这样程序会报错,因为不能直接在主线程进行网络操作。

解决办法

  • 另开子线程
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
new Thread(new Runnable() {
@Override
public void run() {
String url = "https://raw.github.com/square/okhttp/master/README.md";
OkHttpClient okHttpClient = new OkHttpClient();

Request request = new Request.Builder().url(url).build();
okhttp3.Response response = null;
try {
response = okHttpClient.newCall(request).execute();
String json = response.body().string();
Log.i(TAG,json);

} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
  • 异步请求
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
String url = "https://raw.github.com/square/okhttp/master/README.md";
OkHttpClient okHttpClient = new OkHttpClient();

Request request = new Request.Builder().url(url).build();
okhttp3.Response response = null;
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i(TAG, "onFailure: ");
}

@Override
public void onResponse(Call call, Response response) throws IOException {
String json = response.body().string();
Log.i(TAG,json);
}
});

post请求

post提交Json数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
String url = "https://raw.github.com/square/okhttp/master/README.md";
String json = "zzz";
OkHttpClient okHttpClient = new OkHttpClient();

RequestBody body = RequestBody.create(MediaType.parse("application/json"),json);
final Request request = new Request.Builder()
.url(url)
.post(body)
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i(TAG, "onFailure: " + e.toString());
}

@Override
public void onResponse(Call call, Response response) throws IOException {
Log.i(TAG, "onResponse: " + request.body().toString());
}
});

其他的就不再一一列举。