package com.example.btft.utils;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;
import com.example.btft.MyApplication;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
public class TokenInterceptor implements Interceptor {
private static final String TAG = "TokenInterceptor";
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Request.Builder requestBuilder = request.newBuilder();
Headers.Builder headerBuilder = request.headers().newBuilder();
headerBuilder.add("DeviceType","Android");
headerBuilder.add("Version",packageCode(MyApplication.getAppContext()));
requestBuilder.headers(headerBuilder.build());
request = requestBuilder.build();
Response response = chain.proceed(request);
Response response2=response;
Log.d(TAG, "response.code=" + response.code());
SharedPreferences sharedPreferences =
MyApplication.getAppContext().getSharedPreferences("user", Context.MODE_PRIVATE);
int uid = sharedPreferences.getInt("userId", 0);
//响应头有“Token”且不为空时,替换掉旧Token,并重新请求,获取最新结果
Headers headers = response.headers();
for (int i = 0; i < headers.size(); i++) {
if("Token".equals(headers.name(i))){
if(!"".equals(headers.value(i))){
//获取editor对象
SharedPreferences.Editor editor = sharedPreferences.edit();//获取编辑器
//存储键值对
editor.putString("token", headers.value(i));
editor.commit();//提交修改
Request newRequest = chain.request()
.newBuilder()
.removeHeader("Authorization")
.addHeader("Authorization",uid+"_"+headers.value(i))
.build();
//重新请求
response2= chain.proceed(newRequest);
}else{
response2= response;
}
}
}
return response2;
}
public static String packageCode(Context context) {
PackageManager manager = context.getPackageManager();
String code = "";
try {
PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
code = info.versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return code;
}
}
然后在OkHttp中添加拦截器
OkHttpClient okHttpClient = new OkHttpClient.Builder() .addInterceptor(new TokenInterceptor())//添加获取token的拦截器 .build();