拦截器(.addInterceptor())
在请求的过程中会执行一次拦截器中的interceptor方法,此时的请求还未发给服务器。那么可以在interceptor方法中对请求进行修饰,比如,不管是什么接口发起的请求,服务器希望每个请求带上当前的平台、应用的版本号等请求头。
public class InterceptorUnitTest {
private static final String TAG = "InterceptorUnitTest";
@Test
public void interceptor() {
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
@NonNull
@Override
public Response intercept(@NonNull Chain chain) throws IOException {
// 创建和之前请求的request对象一样的Builder对象,然后在此基础上加上其它内容。
Request request = chain.request().newBuilder()
.addHeader("os","Android")
.addHeader("version", BuildConfig.VERSION_NAME)
.build();
// 向服务器发送新的请求
Response response = chain.proceed(request);
return response;
}
}).build();
Request request = new Request.Builder().url("https://www.httpbin.org/get").build();
Call call = client.newCall(request);
try {
Response response = call.execute();
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}
缓存(cache)
默认情况下,OkHttp的缓存是关闭状态,需要我们开启。步骤如下:
-
让OkHttpClient的构建者调用cache方法。
-
配置cache方法,只需要通过new Cache()。
-
为Cache的构造方法传递参数。
file:保存缓存的文件位置。
size:文件的最大大小,如果缓存大小以及超过了文件的大小,那么就会请求当前文件中的内容再存缓存。
其余步骤不变,就是网络请求,具体代码如下:
public class InterceptorUnitTest {
private static final String TAG = "InterceptorUnitTest";
@Test
public void interceptor() {
OkHttpClient client = new OkHttpClient.Builder()
.cache(new Cache(new File("C:\\Users\\杨小亮\\Desktop"),1024*1024))
.addInterceptor(new Interceptor() {
@NonNull
@Override
public Response intercept(@NonNull Chain chain) throws IOException {
// 创建和之前请求的request对象一样的Builder对象,然后在此基础上加上其它内容。
Request request = chain.request().newBuilder()
.addHeader("os","Android")
.addHeader("version", BuildConfig.VERSION_NAME)
.build();
// 向服务器发送新的请求
Response response = chain.proceed(request);
return response;
}
}).build();
Request request = new Request.Builder().url("https://www.httpbin.org/get").build();
Call call = client.newCall(request);
try {
Response response = call.execute();
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}
Cookie
Cookie是为了辨别用户身份、进行会话跟踪而存储在用户本地终端上的数据。
使用步骤:
-
调用cookieJar方法,配置cookieJar方法。
-
传入已经实现了的CookieJar接口。
new CookieJar() { @Override public void saveFromResponse(@NonNull HttpUrl httpUrl, @NonNull List<Cookie> list) { /** * 服务器的cookie数据封装成List集合后通过回调接口返回给我们 * 我们在这个方法中需要做的是将cookie数据保存的本地 */ } @NonNull @Override public List<Cookie> loadForRequest(@NonNull HttpUrl httpUrl) { /** * httpUrl是我们请求的服务器的url,我们需要判断当前请求的url和httpUrl是否相等 * 相等我们就返回刚刚保存好的cookie List集合 */ return null; } }
具体代码:
public class CookieUnitTest {
Map<String,List<Cookie>> cookies = new HashMap<>();
@Test
public void name() {
OkHttpClient client = new OkHttpClient.Builder().cookieJar(new CookieJar() {
@Override
public void saveFromResponse(@NonNull HttpUrl httpUrl, @NonNull List<Cookie> list) {
cookies.put(httpUrl.host(),list);
}
@NonNull
@Override
public List<Cookie> loadForRequest(@NonNull HttpUrl httpUrl) {
List<Cookie> list = cookies.get(httpUrl.host());
return list == null ? new ArrayList<>() : list;
}
}).build();
FormBody formBody = new FormBody.Builder().add("username", "18146614162")
.add("password", "yxl18679937350")
.build();
Request request = new Request.Builder()
.url("https://www.wanandroid.com/user/login")
.post(formBody)
.build();
Call call = client.newCall(request);
try {
Response response = call.execute();
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
request = new Request.Builder().url("https://www.wanandroid.com/lg/collect/list/0/json").build();
call = client.newCall(request);
try {
Response response = call.execute();
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}