之前在找了个网站爬数据有个验证码识别,一直没有办法验证,后来问了大神才知道要用cookie标识的,知道这就好办了,okhttp将cookie拦截存在SheardPreferents里面,在添加至请求头中
联网用的retrofit+okhttp
验证码是图片用的glide
- okhttp添加拦截器代码如下:
new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
okhttp3.Response originalResponse = chain.proceed(chain.request());
if (!originalResponse.headers("Set-Cookie").isEmpty()) {
StringBuilder stringBuilder = new StringBuilder();
for (String header : originalResponse.headers("Set-Cookie")) {
stringBuilder.append(header);
}
SPUtils.saveString(context,Constant.SP.COOKIE,stringBuilder.toString());
}
return originalResponse;
}
})
.addInterceptor(new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
String cookie = SPUtils.getString(context, Constant.SP.COOKIE, null);
Request newRequest = chain.request().newBuilder()
.header("Cookie", cookie != null ? cookie : "")
return chain.proceed(newRequest);
}
})
.connectTimeout(Constant.CONNECT_TIMEOUT, TimeUnit.SECONDS)
.writeTimeout(Constant.CONNECT_TIMEOUT, TimeUnit.SECONDS)
.readTimeout(Constant.CONNECT_TIMEOUT, TimeUnit.SECONDS)
.build();
- Glide添加请求头:
String cookie = SPUtils.getString(applicationContext, Constant.SP.COOKIE, null);
GlideUrl glideUrl = null;
try {
glideUrl = new GlideUrl(new URL(url), new LazyHeaders.Builder()
.setHeader("Cookie", cookie != null ? cookie : "")
.build());
} catch (MalformedURLException e) {
e.printStackTrace();
}
Glide.with(this).load(glideUrl).fitCenter().error(mVerificationCodeFail).diskCacheStrategy(DiskCacheStrategy.NONE).into(mIvVerificationCode);
好了,就是这么简单.